;
(function (window, angular) {
    'use strict';
    angular.module("Controller.Sales.SellIntention", [])
        .controller("SellIntentionCtrl", ["$scope", "$state", "ybWidget", "ybHttp", "MESG_TYPE", "$timeout", "EventBus", "$filter", "UserContextService", "$stateParams", "ybConfig", function ($scope, $state, ybWidget, ybHttp, MESG_TYPE, $timeout, EventBus, $filter, UserContextService, $stateParams, ybConfig) {
            $scope.jckFlag = false;
            $scope.activeFlag = [true, false, false, false, false, false];
            $scope.sourceFlag = null;
            $scope.datePickerFlag = [false, false];
            $scope.subTabFlag = [true, false];
            $scope.TJJXList = [];
            $scope.markInfo = {
                allCheckedBill: false,
                allCheckedMaterial: false,
                allCheckedMaterialDetail: false,
                curRow: -1
            };
            $scope.pageInfo = {
                totalPages: 1,
                totalRows: 0,
                pageSize: 10,
                curPage: 1
            };
            $scope.pageInfoPurchase = {
                totalPages: 1,
                totalRows: 0,
                pageSize: 10,
                curPage: 1
            };
            $scope.submitted = false;
            $scope.condition = {
                isService :$scope.isTJ? $scope.curUser.isService:undefined,
            };
            $scope.billCondition = {};
            $scope.editMaterialList = [];
            $scope.toolbarConfig = {
                showAdvanceSearch: false,
                showColConfig: false,
                showMateriel: false
            };
            $scope.dataList = [];
            $scope.purchaseList = [];
            $scope.isOutSupplier = false;// 供货商是否外采

            $scope.orderObj = {
                headerInfo: {
                    supplierOrgId: $scope.curOrgId,
                    supplierOrgName: $scope.curOrg.companyName,
                    isStockoutStatistics: 1,
                    forward: $scope.isJCHK ? '' : 0
                },
                materialList: [],
                bakMaterialsList: []
            };
            $scope.bakList = [];
            $scope.purchaseLevelList = [];
            $scope.tmonitoringTotalData = {}; //订单监控统计数据
            $scope.isMonitoringViewFlag = false; //是否是订单监控列表页点击意向单号查询详情
            $scope.deliverStatusList = [{
                    id: 0,
                    name: "未出库"
                },
                {
                    id: 1,
                    name: "部分出库"
                },
                {
                    id: 2,
                    name: "已出库"
                },
                {
                    id: 10,
                    name: "未出库+部分出库"
                }
            ];
            $scope.transferList = [
                {
                    code: 0,
                    name: "不接受"
                },
                {
                    code: 1,
                    name: "接受"
                }
            ];
            $scope.deliveryList = [];
            $scope.sellTbConf = {
                fixedWidth: 360,
                scrollWidth: 1380,
                tableCol: [
                    {
                        type: "",
                        name: "意向单号",
                        dataField: "saleNo",
                        width: 180,
                        isShow: true,
                        isFixed: false,
                        clickFn: "viewDetail",
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "客户名称",
                        dataField: "purchaseOrgName",
                        width: 200,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "物流状态",
                        dataField: "deliveryDesc",
                        width: 200,
                        isShow: $scope.isCHY,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "采购单号",
                        dataField: "purchaseNo",
                        width: 120,
                        isShow: !$scope.isJCHK,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "供货商",
                        dataField: "targetOrgName",
                        width: 180,
                        isShow: $scope.isJCHK,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "采购员",
                        dataField: "buyerName",
                        width: 100,
                        isShow: $scope.isJCHK,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "首次提交日期",
                        dataField: "firstSubmitDateShow",
                        width: 130,
                        isShow: $scope.isJCHK || $scope.isJCH || $scope.isNY,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "是否建采购订单",
                        dataField: "isCreatePurchaseOrderShow",
                        width: 120,
                        isShow: $scope.isJCHK,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "由直投生成",
                        dataField: "isDirectStr",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "采购级别",
                        dataField: "purchaseLevelNameShow",
                        width: 150,
                        isShow: !$scope.isJCHK,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        name: "是否超额度",
                        dataField: "degreeFlagShow",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        type: "",
                        name: "发运方式",
                        dataField: "deliverTypeNameShow",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                      type: "",
                      name: "总价",
                      dataField: "totalDiscountPrice",
                      width: 150,
                      isShow: $scope.isNJ,
                      isFixed: false,
                      toSort: false,
                      sortType: ""
                    },
                    {
                        type: "attach",
                        name: "附件",
                        dataField: "attachName",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        clickFn: "downloadAttach",
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "创建方式",
                        dataField: "createTypeShow",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "创建人",
                        dataField: "createName",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "制单时间",
                        dataField: "createDateShows",
                        width: 130,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "发货通知状态",
                        dataField: "deliverStatusShow",
                        width: 110,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "出库状态",
                        dataField: "inventoryOutStatusShow",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "退货申请状态",
                        dataField: "applyReturnShow",
                        width: 120,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "同步状态",
                        dataField: "syncNsStatusShow",
                        width: 120,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "CRM单号",
                        dataField: "crmOrder",
                        width: 180,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "前移单号",
                        dataField: "pmsCode",
                        width: 180,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "组织架构",
                        dataField: "deptName",
                        width: 180,
                        isShow: $scope.isJCHK,
                        isFixed: false
                    },
                    {
                        name: "是否前移",
                        dataField: "forwardShow",
                        width: 100,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        name: "价格是否修改",
                        dataField: "modifyPriceFlagShow",
                        width: 120,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        name: "是否打印",
                        dataField: "isPrintShow",
                        width: 120,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        name: "单据状态",
                        dataField: "statusShow",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "审核状态",
                        dataField: "checkFlagShow",
                        width: 100,
                        isShow: $scope.isJCH||$scope.isLDD||$scope.isNY||$scope.isNJ,
                        isFixed: false,
                    },
                    {
                        name: "删除申请原因",
                        dataField: "deleteApplicationReason",
                        width: 120,
                        isShow: $scope.isKJ,
                        isFixed: false,
                    },
                    {
                        name: "删除审核意见",
                        dataField: "deleteAuditOpinion",
                        width: 120,
                        isShow: $scope.isKJ,
                        isFixed: false,
                    },
                    {
                        type: "operate",
                        name: "操作",
                        dataField: "",
                        width: 320,
                        isShow: true,
                        isFixed: true,
                        toSort: false,
                        sortType: ""
                    }
                ]
            };
            $scope.purchaseTbConf = {
                fixedWidth: 120,
                scrollWidth: 980,
                tableCol: [{
                        type: "",
                        name: "采购申请单号",
                        dataField: "billNo",
                        width: 180,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "客户名称",
                        dataField: "purchaseOrgName",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "发运方式",
                        dataField: "sendType",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "调度员",
                        dataField: "dispatcherName",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "申请人",
                        dataField: "createName",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "申请公司",
                        dataField: "purchaseOrgName",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "申请时间",
                        dataField: "createDateShow",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "采购级别",
                        dataField: "purchaseLevel",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "审核状态",
                        dataField: "statusDesc",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        name: "国家",
                        dataField: "country",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        type: "operate",
                        name: "操作",
                        dataField: "",
                        width: 120,
                        isShow: true,
                        isFixed: true,
                        toSort: false,
                        sortType: ""
                    }
                ]
            };
            $scope.detailMap = [
                {
                    name: '销售意向单',
                    field: 'saleNo',
                    isShow: true,
                },
                {
                    name: '客户名称',
                    isShow: true,
                    field: 'purchaseOrgName'
                },
                {
                    name: "供货商",
                    isShow:  $scope.isJCHK,
                    field: 'targetOrgName'
                },
                {
                    name: '采购员',
                    isShow:  $scope.isJCHK,
                    field: 'buyerName'
                },
                {
                    name: '申请日期',
                    isShow: true,
                    field: 'createDateShow'
                },
                {
                    name: '采购单号',
                    isShow: true,
                    field: 'purchaseNo'
                },
                {
                    name: '采购合同单号',
                    isShow: true,
                    field: 'purchaseContractNo'
                },
                {
                    name: '合同号',
                    isShow: true,
                    field: 'contractNo'
                },
                {
                    name: '交货日期',
                    isShow: true,
                    field: 'deliveryDateShow'
                },
                {
                    name: '采购级别',
                    isShow: true,
                    field: 'purchaseLevelNameShow'
                },
                {
                    name: '是否赠送',
                    isShow: false,
                    field: 'giftFlagShow'
                },
                {
                    name: '发运方式',
                    isShow: true,
                    field: 'deliverTypeNameShow'
                },
                {
                    name: '结算方式',
                    isShow: true,
                    field: 'settleTypeName'
                },
                {
                    name: '收货人',
                    isShow: true,
                    field: 'receiverName',
                    inputType: 'input'
                },
                {
                    name: '联系方式',
                    isShow: true,
                    field: 'receiverPhone',
                    inputType: 'input'
                },
                {
                    name: '收货地址',
                    isShow: true,
                    field: 'receiveAddress',
                    inputType: 'input'
                },
                {
                    name: '传真',
                    isShow: true,
                    field: 'receiverFax'
                },
                {
                    name: '订单总价',
                    isShow: true,
                    field: 'totalSettlementPrice'
                },
                {
                    name: '调整总价',
                    isShow: true,
                    field: 'totalDiscountPrice'
                },
                {
                    name: '国家和地区',
                    isShow: true,
                    field: 'country'
                },
                {
                    name: '地区',
                    isShow: true,
                    field: 'region'
                },
                {
                    name: '合同',
                    isShow: true,
                    field: 'contract'
                },
                {
                    name: '机型',
                    isShow: true,
                    field: 'model'
                },
                {
                    name: 'CRM单号',
                    isShow: true,
                    field: 'crmOrder'
                },
                {
                    name: '是否前移',
                    isShow: true,
                    field: 'forward'
                },
                {
                    name: '前移单号',
                    isShow: true,
                    field: 'pmsCode'
                },
                {
                    name: '备注',
                    field: 'remark',
                    isShow: true,
                    inputType: 'input'
                },
                {
                    name: '尾差金额',
                    field: 'cashShortAndOver',
                    inputType: 'input',
                    isShow: $scope.isTJ
                },
                {
                    name: '币种',
                    field: 'currency',
                    isShow: true
                },
                {
                    name: '外销总价',
                    field: 'totalExportPrice',
                    isShow: true
                },
                {
                    name: '分销类型',
                    field: 'distributionTypeShow',
                    isShow: $scope.isJCHK
                }
            ];
            $scope.detailPriceMap = [
                {
                    name: '销售意向单',
                    field: 'saleNo',
                    isShow: true,
                },
                {
                    name: '客户名称',
                    isShow: true,
                    field: 'purchaseOrgName'
                },
                {
                    name: "供货商",
                    isShow:  $scope.isJCHK,
                    field: 'targetOrgName'
                },
                {
                    name: '采购员',
                    isShow:  $scope.isJCHK,
                    field: 'buyerName'
                },
                {
                    name: '申请日期',
                    isShow: true,
                    field: 'createDateShow'
                },
                {
                    name: '采购单号',
                    isShow: true,
                    field: 'purchaseNo'
                },
                {
                    name: '采购合同单号',
                    isShow: true,
                    field: 'purchaseContractNo'
                },
                {
                    name: '合同号',
                    isShow: true,
                    field: 'contractNo'
                },
                {
                    name: '交货日期',
                    isShow: true,
                    field: 'deliveryDateShow'
                },
                {
                    name: '采购级别',
                    isShow: true,
                    field: 'purchaseLevelNameShow'
                },
                {
                    name: '是否赠送',
                    isShow: false,
                    field: 'giftFlagShow'
                },
                {
                    name: '发运方式',
                    isShow: true,
                    field: 'deliverTypeNameShow'
                },
                {
                    name: '结算方式',
                    isShow: true,
                    field: 'settleTypeName'
                },
                {
                    name: '收货人',
                    isShow: true,
                    field: 'receiverName',
                },
                {
                    name: '联系方式',
                    isShow: true,
                    field: 'receiverPhone',
                },
                {
                    name: '收货地址',
                    isShow: true,
                    field: 'receiveAddress',
                },
                {
                    name: '传真',
                    isShow: true,
                    field: 'receiverFax'
                },
                {
                    name: '订单总价',
                    isShow: true,
                    field: 'totalSettlementPrice'
                },
                {
                    name: '调整总价',
                    isShow: true,
                    field: 'totalDiscountPrice'
                },
                {
                    name: '国家和地区',
                    isShow: true,
                    field: 'country'
                },
                {
                    name: '地区',
                    isShow: true,
                    field: 'region'
                },
                {
                    name: '合同',
                    isShow: true,
                    field: 'contract'
                },
                {
                    name: '机型',
                    isShow: true,
                    field: 'model'
                },
                {
                    name: 'CRM单号',
                    isShow: true,
                    field: 'crmOrder'
                },
                {
                    name: '是否前移',
                    isShow: true,
                    field: 'forward'
                },
                {
                    name: '前移单号',
                    isShow: true,
                    field: 'pmsCode'
                },
                {
                    name: '备注',
                    field: 'remark',
                    isShow: true,
                },
                {
                    name: '尾差金额',
                    field: 'cashShortAndOver',
                    isShow: $scope.isTJ
                },
                {
                    name: '币种',
                    field: 'currency',
                    isShow: true
                },
                {
                    name: '外销总价',
                    field: 'totalExportPrice',
                    isShow: true
                },
                {
                    name: '分销类型',
                    field: 'distributionTypeShow',
                    isShow: $scope.isJCHK
                }
            ];
            $scope.viewTbConf = {
                scrollWidth: 1980,
                tableCol: [
                    {
                        type: "",
                        name: "行号",
                        dataField: "lineNo",
                        width: 80,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        name: "零件编号",
                        width: 150,
                        dataField: "materialsNo"
                    },
                    {
                        name: "原零件号",
                        width: 150,
                        dataField: "originalMaterialsNo"
                    },
                    {
                        name: "零件中文名",
                        width: 150,
                        dataField: "materialsDes"
                    },
                    {
                        name: "是否冻结",
                        width: 100,
                        dataField: "isFrozenShow"
                    }, //add by spd
                    {
                        name: "零件分类",
                        width: 100,
                        dataField: "materialsType"
                    },
                    {
                        name: "单位",
                        width: 100,
                        dataField: "unit"
                    },
                    {
                        name: "适用机型",
                        width: 100,
                        dataField: "machineModel",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "申请数量",
                        width: 100,
                        dataField: "qty"
                    },
                    {
                        name: "单价",
                        width: 100,
                        dataField: "price",
                        hidden: false
                    },
                    {
                        name: "申请总价",
                        width: 100,
                        dataField: "applyTotalPrice",
                        hidden: false
                    },
                    {
                        name: "外销价格方案",
                        width: 100,
                        dataField: "exportPriceSchemeName"
                    },
                    {
                        name: "价格方案",
                        width: 100,
                        dataField: "priceSchemeName"
                    },
                    {
                        name: "调整后数量",
                        width: 100,
                        dataField: "amountAfterAdjust"
                    },
                    {
                        name: "调整后单价",
                        width: 100,
                        dataField: "unitPriceAfterAdjust"
                    },
                    {
                        name: "调整后总价",
                        width: 100,
                        dataField: "totalPriceAfterAdjust"
                    },
                    {
                        name: "折扣比例",
                        width: 130,
                        dataField: "discountRate",
                        hidden: !$scope.isNY,
                    },
                    {
                        name: "标准价",
                        width: 100,
                        dataField: "standardPrice",
                        hidden: !$scope.isJCH, // 仅限基础
                    },
                    {
                        name: "外销单价",
                        width: 100,
                        dataField: "exportPrice",
                        hidden: !$scope.isJCHK, // 仅限进出口
                    },
                    {
                        name: "外销金额",
                        width: 100,
                        dataField: "totalExportPrice",
                        hidden: !$scope.isJCHK, // 仅限进出口
                    },
                    {
                        name: "创建发货数量",
                        width: 120,
                        dataField: "informedAmount"
                    },
                    {
                        name: "实际出库数量",
                        width: 120,
                        dataField: "inventoryOutAmount"
                    },
                    {
                        name: "实际库存",
                        width: 100,
                        dataField: "enableNum"
                    },
                    {
                        name: "大厂库存",
                        width: 100,
                        clickFnDaChang: "dachangStock",
                    },
                    {
                        name: "意向占用",
                        width: 120,
                        dataField: "intentionNum"
                    },
                    {
                        name: "发货占用",
                        width: 120,
                        dataField: "deliveryNum"
                    },
                    {
                        name: "交货日期",
                        width: 150,
                        dataField: "requestDeliveryDateShow"
                    },
                    {
                      name: "标准交期",
                      width: 150,
                      dataField: "standDeliveryTime",
                    },
                    {
                        name: "预计发货日期",
                        dataField: "estimatedShippingDateShow",
                        width: 130,
                    },
                    {
                        name: "备注",
                        width: 150,
                        dataField: "remark"
                    }
                ]
            };
            $scope.adjustTbConf = {
                scrollWidth: 1980,
                tableCol: [
                    {
                        type: "",
                        name: "行号",
                        dataField: "lineNo",
                        width: 80,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        name: "零件编号",
                        width: 150,
                        dataField: "materialsNo"
                    },
                    {
                        name: "原零件号",
                        width: 150,
                        dataField: "originalMaterialsNo"
                    },
                    {
                        name: "零件中文名",
                        width: 150,
                        dataField: "materialsDes"
                    },
                    {
                        name: "零件分类",
                        width: 100,
                        dataField: "materialsType"
                    },
                    {
                        name: "单位",
                        width: 100,
                        dataField: "unit"
                    },
                    {
                        name: "适用机型",
                        width: 100,
                        dataField: "machineModel",
                        input: true,
                        inputType: "machineModel"
                    },
                    {
                        name: "是否加价",
                        width: 80,
                        dataField: "isNeedRaise",
                        hidden: true,
                        input: true,
                        inputType: "checkbox",
                        isChecked: ""
                    },
                    {
                        name: "申请数量",
                        width: 100,
                        dataField: "qty"
                    },
                    {
                        name: "单价",
                        width: 100,
                        dataField: "price",
                    },
                    {
                        name: "申请总价",
                        width: 100,
                        dataField: "applyTotalPrice",
                    },
                    {
                        name: "价格方案",
                        width: 100,
                        dataField: "priceSchemeName",
                        input: true,
                        inputType: "func"
                    },
                    {
                        name: "外销价格方案",
                        width: 140,
                        dataField: "exportPriceSchemeName",
                        input: true,
                        inputType: "funcWX",
                        hidden: !$scope.isJCHK,
                    },
                    {
                        name: "外销单价",
                        width: 100,
                        dataField: "exportPrice",
                        hidden: !$scope.isJCHK,
                        input: true,
                        inputType: "waixiaoPrice"
                    },
                    {
                        name: "外销金额",
                        width: 100,
                        dataField: "totalExportPrice",
                        hidden: !$scope.isJCHK,
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "调整后数量",
                        width: 100,
                        dataField: "amountAfterAdjust",
                        input: true,
                        inputType: "num"
                    },
                    {
                        name: "调整后单价",
                        width: 100,
                        dataField: "unitPriceAfterAdjust",
                        input: true,
                        inputType: "unitPriceAfterAdjust"
                    },
                    {
                        name: "折扣比例",
                        width: 130,
                        dataField: "discountRate",
                        input: false,
                        inputType: "",
                        hidden: !$scope.isNY,
                    },
                    {
                        name: "调整后总价",
                        width: 100,
                        dataField: "totalPriceAfterAdjust"
                    },
                    {
                        name: "创建发货数量",
                        width: 120,
                        dataField: "informedAmount"
                    },
                    {
                        name: "实际出库数量",
                        width: 120,
                        dataField: "inventoryOutAmount"
                    },
                    {
                        name: "实际库存",
                        width: 100,
                        dataField: "enableNum"
                    },
                    {
                        name: "意向占用",
                        width: 120,
                        dataField: "intentionNum"
                    },
                    {
                        name: "发货占用",
                        width: 120,
                        dataField: "deliveryNum"
                    },
                    {
                        name: "交货日期",
                        width: 150,
                        dataField: ($scope.isDL || $scope.isZHL) ? 'requestDeliveryDate' : "requestDeliveryDateShow",
                        input: $scope.isDL || $scope.isZHL,
                        inputType: "time"
                    },
                    {
                      name: "标准交期",
                      width: 150,
                      dataField: "standDeliveryTime",
                    },
                    {
                        name: "预计发货日期",
                        dataField: "estimatedShippingDateShow",
                        width: 130,
                    },
                    {
                        name: "备注",
                        width: 150,
                        dataField: "remark"
                    },
                    {
                        name: "价格修改人",
                        width: 120,
                        dataField: "modifyPriceUser"
                    },
                    {
                        name: "价格最后修改时间",
                        width: 140,
                        dataField: "modifyPriceTimeShow"
                    },
                ]
            };
            $scope.editTbConf = { // 手动制定
                scrollWidth: 1910,
                tableCol: [
                    {
                        type: "",
                        name: "行号",
                        dataField: "lineNo",
                        width: 80,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        name: "零件编号",
                        width: 150,
                        dataField: "materialsNo",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "原零件号",
                        width: 150,
                        dataField: "originalMaterialsNo",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "零件中文名",
                        width: 200,
                        dataField: "materialsDes",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "是否冻结",
                        width: 100,
                        dataField: "isFrozenShow"
                    }, //add by spd
                    {
                        name: "零件分类",
                        width: 100,
                        dataField: "materialsType"
                    },
                    {
                        name: "单位",
                        width: 80,
                        dataField: "unit",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "适用机型",
                        width: 100,
                        dataField: "machineModel",
                        input: true,
                        inputType: ""
                    },
                    {
                        name: "申请数量",
                        width: 80,
                        dataField: "qty",
                        input: true,
                        inputType: "num"
                    },
                    {
                        name: "单价",
                        width: 100,
                        dataField: "price",
                        hidden: $scope.isJCHK,
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "申请总价",
                        width: 100,
                        dataField: "applyTotalPrice",
                        hidden: $scope.isJCHK,
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "是否加价",
                        width: 80,
                        dataField: "isNeedRaise",
                        hidden: true,
                        input: true,
                        inputType: "checkbox",
                        isChecked: ""
                    },
                    {
                        name: "价格方案",
                        width: 140,
                        dataField: "priceSchemeName",
                        input: true,
                        inputType: "func"
                    },
                    {
                        name: "外销价格方案",
                        width: 140,
                        dataField: "exportPriceSchemeName",
                        input: true,
                        inputType: "funcWX",
                        hidden: !$scope.isJCHK,
                    },
                    {
                        name: "外销单价",
                        width: 100,
                        dataField: "exportPrice",
                        hidden: !$scope.isJCHK,
                        input: true,
                        inputType: "waixiaoPrice"
                    },
                    {
                        name: "外销金额",
                        width: 100,
                        dataField: "totalExportPrice",
                        hidden: !$scope.isJCHK,
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "调整后数量",
                        width: 100,
                        dataField: "amountAfterAdjust",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "调整后单价",
                        width: 130,
                        dataField: "unitPriceAfterAdjust",
                        input: true,
                        inputType: "price"
                    },
                    {
                        name: "调整后总价",
                        width: 130,
                        dataField: "totalPriceAfterAdjust",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "折扣比例",
                        width: 130,
                        dataField: "discountRate",
                        input: false,
                        inputType: "",
                        hidden: !$scope.isNY,
                    },
                    {
                        name: "标准价",
                        width: 130,
                        dataField: "standardPrice",
                        hidden: !$scope.isJCH, // 仅限基础
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "实际库存",
                        width: 100,
                        clickFn: "alterReport",
                        dataField: "enableNum"
                    },
                    {
                        name: "大厂库存",
                        width: 100,
                        clickFnDaChang: "dachangStock",
                        hidden: $scope.isJCHK,
                    },
                    {
                        name: "意向占用",
                        width: 120,
                        dataField: "intentionNum"
                    },
                    {
                        name: "发货占用",
                        width: 120,
                        dataField: "deliveryNum"
                    },
                    {
                        name: "交货日期",
                        width: 150,
                        dataField: "requestDeliveryDate",
                        input: true,
                        inputType: "time"
                    },
                    {
                      name: "标准交期",
                      width: 150,
                      dataField: "standDeliveryTime",
                    },
                    {
                        name: "预计发货日期",
                        dataField: "estimatedShippingDateShow",
                        width: 130,
                    },
                    {
                        name: "备注",
                        width: 150,
                        dataField: "remark",
                        input: true,
                        inputType: "note"
                    },
                    {
                        name: "替换零件",
                        width: 150,
                        needWarn: true,
                        dataField: "replaceMaterialsNo",
                        hidden: !$scope.isJCHK
                    },
                    {
                        name: "替换零件中文名",
                        width: 150,
                        needWarn: true,
                        dataField: "replaceMaterialsDes",
                        hidden: !$scope.isJCHK
                    },
                    {
                        name: "价格修改人",
                        width: 120,
                        dataField: "modifyPriceUser"
                    },
                    {
                        name: "价格最后修改时间",
                        width: 140,
                        dataField: "modifyPriceTimeShow"
                    },
                ]
            };
            $scope.autoEditTbConf = { // 自动制定
                scrollWidth: 1910,
                tableCol: [
                    {
                        type: "",
                        name: "行号",
                        dataField: "lineNo",
                        width: 80,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        name: "零件编号",
                        width: 150,
                        dataField: "materialsNo",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "原零件号",
                        width: 150,
                        dataField: "originalMaterialsNo",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "零件中文名",
                        width: 200,
                        dataField: "materialsDes",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "是否冻结",
                        width: 100,
                        dataField: "isFrozenShow"
                    }, //add by spd
                    {
                        name: "零件分类",
                        width: 100,
                        dataField: "materialsType"
                    },
                    {
                        name: "单位",
                        width: 80,
                        dataField: "unit",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "适用机型",
                        width: 100,
                        dataField: "machineModel",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "申请数量",
                        width: 80,
                        dataField: "qty",
                        input: true,
                        inputType: "num"
                    },
                    {
                        name: "单价",
                        width: 100,
                        dataField: "price",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "申请总价",
                        width: 100,
                        dataField: "applyTotalPrice",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "是否接受调拨",
                        width: 80,
                        dataField: "transferFlag",
                        hidden: true,
                        input: true,
                        inputType: "select",
                        isChecked: ""
                    },
                    {
                        name: "是否加价",
                        width: 80,
                        dataField: "isNeedRaise",
                        hidden: true,
                        input: true,
                        inputType: "checkbox",
                        isChecked: ""
                    },
                    {
                        name: "价格方案",
                        width: 140,
                        dataField: "priceSchemeName",
                        input: true,
                        inputType: "func"
                    },
                    {
                        name: "外销价格方案",
                        width: 140,
                        dataField: "exportPriceSchemeName",
                        input: true,
                        inputType: "funcWX",
                        hidden: !$scope.isJCHK,
                    },
                    {
                        name: "外销单价",
                        width: 100,
                        dataField: "exportPrice",
                        hidden: !$scope.isJCHK, // 仅限进出口
                        input: true,
                        inputType: "waixiaoPrice"
                    },
                    {
                        name: "外销金额",
                        width: 100,
                        dataField: "totalExportPrice",
                        hidden: !$scope.isJCHK,
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "调整后数量",
                        width: 100,
                        dataField: "amountAfterAdjust",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "调整后单价",
                        width: 130,
                        dataField: "unitPriceAfterAdjust",
                        input: true,
                        inputType: "price"
                    },
                    {
                        name: "折扣比例",
                        width: 130,
                        dataField: "discountRate",
                        input: false,
                        inputType: "",
                        hidden: !$scope.isNY,
                    },
                    {
                        name: "调整后总价",
                        width: 130,
                        dataField: "totalPriceAfterAdjust",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "标准价",
                        width: 130,
                        dataField: "standardPrice",
                        hidden: !$scope.isJCH, // 仅限基础
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "实际库存",
                        width: 100,
                        clickFn: "alterReport",
                        dataField: "enableNum"
                    },
                    {
                        name: "大厂库存",
                        width: 100,
                        clickFnDaChang: "dachangStock",
                    },
                    {
                        name: "意向占用",
                        width: 120,
                        dataField: "intentionNum"
                    },
                    {
                        name: "发货占用",
                        width: 120,
                        dataField: "deliveryNum"
                    },
                    {
                        name: "交货日期",
                        width: 150,
                        dataField: "requestDeliveryDate",
                        input: true,
                        inputType: "time"
                    },
                    {
                        name: "备注",
                        width: 150,
                        dataField: "remark",
                        input: true,
                        inputType: "note"
                    },
                    {
                        name: "替换零件",
                        width: 150,
                        needWarn: true,
                        dataField: "replaceMaterialsNo",
                        hidden: !$scope.isJCHK
                    },
                    {
                        name: "替换零件中文名",
                        width: 150,
                        needWarn: true,
                        dataField: "replaceMaterialsDes",
                        hidden: !$scope.isJCHK
                    },
                    {
                        name: "标准交期",
                        width: 150,
                        dataField: "standDeliveryTime",
                    },
                    {
                        name: "预计发货日期",
                        dataField: "estimatedShippingDateShow",
                        width: 130,
                    },
                    {
                        name: "价格修改人",
                        width: 120,
                        dataField: "modifyPriceUser"
                    },
                    {
                        name: "价格最后修改时间",
                        width: 140,
                        dataField: "modifyPriceTimeShow"
                    },
                ]
            };
            $scope.deliveryTbConf = {
                scrollWidth: 800,
                tableCol: [{
                        type: "",
                        name: "发货通知单号",
                        dataField: "deliveryNo",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "客户名称",
                        dataField: "purchaseOrgName",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "结算方式",
                        dataField: "settleTypeName",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "申请人",
                        dataField: "createName",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "申请日期",
                        dataField: "createDateShow",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "出库状态",
                        dataField: "isOutDesc",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "物流状态",
                        dataField: "logState",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "冲销状态",
                        dataField: "isReverseShow",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    }
                ]
            };

            $scope.receiptTableInfo = {
                tableConfig: {
                    scrollWidth: 750,
                    tableCol: [{
                            name: "单据编号",
                            dataField: "billNo",
                            width: 160,
                            isShow: true,
                            type: "click",
                            clickFn: "viewOrderDetail"
                        },
                        {
                            name: "单据类型",
                            dataField: "billSingleF",
                            width: 100,
                            isShow: true
                        },
                        {
                            name: "单据创建时间",
                            dataField: "billDateF",
                            width: 130,
                            isShow: true
                        },
                        {
                            name: "单据总金额",
                            dataField: "totalPrice",
                            width: 100,
                            isShow: true
                        },
                        {
                            name: "已收金额",
                            dataField: "receivePrice",
                            width: 100,
                            isShow: true
                        },
                        {
                            name: "应收金额",
                            dataField: "remainPrice",
                            width: 100,
                            isShow: true
                        },
                        {
                            name: "本次收款金额",
                            dataField: "checkPrice",
                            width: 120,
                            isShow: true
                        }
                    ]
                },
                dataList: [],
                toSort: function (config, index) {
                    ybWidget.ToSort(config, index);
                },
                tdClick: function (item, fnType) {
                    switch (fnType) {
                        case "viewOrderDetail":
                            viewOrderDetail(item);
                            break;
                        default:
                            break;
                    }
                }
            };

            $scope.exportParam = {
                sectionUrl: ybHttp.RequestUrl("device", "/saleIntention/export"),
                sectionParam: {
                    ids: []
                },
                allUrl: ybHttp.RequestUrl("device", "/saleIntention/exportAll")
            };
            $scope.actionType = 0; // 0: 自动新增 1:手动新增、编辑 3:合同新增
            $scope.tabFlag = {};
            var tabFlag = {
                0: "手动制定",
                1: "编辑",
                2: "自动制定",
                3: "查看",
                4: "审核",
                5: "按合同创建",
                6: "超额度审核"
            };

            var btnPermissionCode = {
                sellIntentionAdd: window.ActionCode.sellIntentionAdd,
                sellIntentionAddAuto: window.ActionCode.sellIntentionAddAuto,
                sellIntentionEdit: window.ActionCode.sellIntentionEdit,
                sellIntentionExport: window.ActionCode.sellIntentionExport,
                sellIntentionAdjust: window.ActionCode.sellIntentionAdjust,
                sellIntentionPriceAdjust: window.ActionCode.sellIntentionPriceAdjust,
                sellIntentionDel: window.ActionCode.sellIntentionDel,
                sellIntentionSynPrice: window.ActionCode.sellIntentionSynPrice,
                sellIntentionImport: window.ActionCode.sellIntentionImport,
                sellIntentionTJ: window.ActionCode.sellIntentionTJ, // wangcan:塔机按照CRM单号
                sellIntentionSyncSaleIntention4NS: window.ActionCode.sellIntentionSyncSaleIntention4NS,
                sellIntentionPriceCanLower: window.ActionCode.sellIntentionPriceCanLower,
                sellIntentionAudit: window.ActionCode.sellIntentionAudit,
                sellIntentionDegreeAudit: window.ActionCode.sellIntentionDegreeAudit,
                sellIntentionDelApply: window.ActionCode.sellIntentionDelApply,
                sellIntentionDelCheck: window.ActionCode.sellIntentionDelCheck,
            };

            $scope.btnPermission = {
                sellIntentionAdd: true,
                sellIntentionAddAuto: true,
                sellIntentionEdit: true,
                sellIntentionExport: true,
                sellIntentionAdjust: true,
                sellIntentionDel: true,
                sellIntentionSynPrice: true,
                sellIntentionImport: true,
                sellIntentionTJ: true,
                sellIntentionSyncSaleIntention4NS : true,
                sellIntentionPriceCanLower : true,
                sellIntentionAudit : true,
                sellIntentionDegreeAudit : true,
                sellIntentionDelApply : true,
                sellIntentionDelCheck : true,
                sellIntentionPriceAdjust: true
            };

            function setBtnPermission() {
                for (var key in btnPermissionCode) {
                    $scope.btnPermission[key] = UserContextService.CheckPermission([btnPermissionCode[key]]);
                }
            }

            $scope.setFixedWidth = function () {
                $scope.tbStyle = {
                    sellFixedWidth: {
                        left: $scope.sellTbConf.fixedWidth + "px"
                    },
                    scrollLeftWidth: {
                        width: $scope.sellTbConf.fixedWidth + "px"
                    },
                    purchaseFixedWidth: {
                        left: $scope.purchaseTbConf.fixedWidth + "px"
                    },
                    contractFixedWidth: {
                        left: $scope.contractTbConf.fixedWidth + "px"
                    },
                    monitoringFixedWidth: {
                        left: $scope.monitoringTbConf.fixedWidth + "px"
                    }
                };
            };

            $scope.changeTab = function (index) {
                $scope.activeFlag = [false, false, false, false, false, false];
                $scope.activeFlag[index] = true;
                $scope.submitted = false;
                $scope.tabFlag.index = index;
                ybWidget.GetTableCol($scope.editTbConf.tableCol, 'isNeedRaise').hidden = true;
                $scope.editTbConf.scrollWidth = 1910;

                ybWidget.GetTableCol($scope.autoEditTbConf.tableCol, 'isNeedRaise').hidden = true;
                $scope.autoEditTbConf.scrollWidth = 1910;

                switch (index) {
                    case 0:
                        initData();
                        break;
                    case 1:
                        break;
                    case 2:
                        initData();
                        break;
                    case 3:
                        break;
                    case 4:
                        break;
                    case 5:
                        break;
                    default:
                        break;
                }
            };

            function initData() {
                $scope.orderObj = {
                    headerInfo: {
                        isStockoutStatistics: 1
                    },
                    materialList: [],
                    bakMaterialsList: []
                };
                $scope.bakList = [];
                $scope.tabFlag = {};
                $scope.editMaterialList = [];
                $scope.markInfo.allCheckedMaterial = false;
                $scope.markInfo.allCheckedMaterialDetail = false;
                $scope.markInfo.allCheckedMonitoring = false;
                $scope.toolbarConfig.showMateriel = false;
                $scope.orderObj.headerInfo.discountPrice = 0;

                ybWidget.GetTableCol($scope.editTbConf.tableCol, 'qty').input = true;
                ybWidget.GetTableCol($scope.editTbConf.tableCol, 'qty').inputType = "num";
                ybWidget.GetTableCol($scope.editTbConf.tableCol, 'amountAfterAdjust').input = false;
                ybWidget.GetTableCol($scope.editTbConf.tableCol, 'amountAfterAdjust').inputType = "";

                ybWidget.GetTableCol($scope.autoEditTbConf.tableCol, 'qty').input = true;
                ybWidget.GetTableCol($scope.autoEditTbConf.tableCol, 'qty').inputType = "num";
                ybWidget.GetTableCol($scope.autoEditTbConf.tableCol, 'amountAfterAdjust').input = false;
                ybWidget.GetTableCol($scope.autoEditTbConf.tableCol, 'amountAfterAdjust').inputType = "";

                ybWidget.GetTableCol($scope.editTbConf.tableCol, 'estimatedShippingDateShow').hidden = false;
                ybWidget.GetTableCol($scope.editTbConf.tableCol, 'standDeliveryTime').hidden = false;
                ybWidget.GetTableCol($scope.autoEditTbConf.tableCol, 'estimatedShippingDateShow').hidden = false;
                ybWidget.GetTableCol($scope.autoEditTbConf.tableCol, 'standDeliveryTime').hidden = false;

                $scope.supplyOrgId = '';
            }

            function getDataList(curPage) {
                $scope.markInfo = {
                    allCheckedBill: false,
                    allCheckedMaterial: false,
                    curRow: -1
                };
                $scope.exportParam.sectionParam.ids = [];
                var service = "device";
                var reqUrl = "/saleIntention/list";
                if (!!curPage) {
                    $scope.pageInfo.curPage = curPage;
                }
                var param = {
                    pageSize: $scope.pageInfo.pageSize,
                    pageNum: $scope.pageInfo.curPage,
                    filters: angular.copy($scope.condition)
                };
                return ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    angular.forEach(resp.value.list, function (item) {
                        item.isChecked = false;
                        item.createTypeShow = $filter("CreateWay")(item.createType);
                        item.createDateShow = $filter("YbDate")(item.createDate);
                        item.deliveryDateShow = $filter("YbDate")(item.deliveryDate);
                        item.createDateShows = $filter("YbDate")(item.createDate, 'yyyy-MM-dd HH:mm:ss');
                        item.deliverStatusShow = $filter("ProgressStatus")(item.deliverStatus);
                        item.inventoryOutStatusShow = $filter("ProgressStatus")(item.inventoryOutStatus, "outDepot");
                        item.isReturnShow = $filter("ProgressStatus")(item.isReturn, "returnState");
                        item.applyReturnShow = $filter("ProgressStatus")(item.applyReturn, "returnApply");
                        item.syncNsStatusShow = $filter("ProgressStatus")(item.syncNsStatus, "sellIntentionSyncNsStatus");
                        item.isDirectStr = $filter("TrueOrFalse")(item.isDirect);
                        item.purchaseLevelNameShow = item.purchaseTypeChildId ? item.purchaseLevelName + "-" + item.purchaseTypeChildName : item.purchaseLevelName;
                        item.deliverTypeNameShow = item.sendTypeChildId ? item.deliverTypeName + "-" + item.sendTypeChildName : item.deliverTypeName;
                        item.statusShow = $filter("Status")(Number(item.status));
                        item.checkFlagShow = $filter("CheckFlagStatus")(item.checkFlag);
                        item.firstSubmitDateShow =  $filter("YbDate")(item.firstSubmitDate, 'yyyy-MM-dd HH:mm:ss');
                        item.isCreatePurchaseOrderShow = $filter("TrueOrFalse")(item.isCreatePurchaseOrder);
                        item.forwardShow = $filter("TrueOrFalse")(item.forward);
                        item.modifyPriceFlagShow = $filter("TrueOrFalse")(item.modifyPriceFlag);
                        item.isPrintShow = $filter("TrueOrFalse")(item.isPrint);
                        item.degreeFlagShow = $filter("TrueOrFalse")(item.degreeFlag);
                    });
                    $scope.pageInfo.totalRows = resp.value.total;
                    $scope.pageInfo.totalPages = resp.value.pages;
                    $scope.dataList = resp.value.list;
                    return resp.value.list
                });
            }

            $scope.toSort = function () {};

            $scope.selectRow = function (index) {
                $scope.markInfo.curRow = index
            };

            $scope.tdClick = function (item, fnType) {
                switch (fnType) {
                    case "viewDetail":
                        ybWidget.GetTableCol($scope.viewTbConf.tableCol, 'enableNum').hidden = $scope.needHide;
                        $scope.isMonitoringViewFlag = false;
                        viewDetail(item);
                        break;
                    case "alterReport":
                        alterReport(item);
                        break;
                    case "downloadAttach":
                        downloadAttach(item);
                        break;
                    case "dachangStock":
                        // 大厂库存点击事件
                        dachangStock(item);
                        break;
                    case "viewMonitoringDetail":
                        // 查看订单监控明细
                        ybWidget.GetTableCol($scope.viewTbConf.tableCol, 'enableNum').hidden = $scope.needHide;
                        $scope.isMonitoringViewFlag = true;
                        viewDetail(item);
                        break;
                    default:
                        break;
                }
            };

            function downloadAttach(item) {
                window.location.href = ybHttp.RequestUrl("device", "/saleIntention/downloadAttach") + '?billId=' + item.id;
            }

            function alterReport(item) {
                var param = {
                    materialsNo: item.materialsNo
                };
                ybWidget.StorageReport(param);
            }

            $scope.switchToolbar = function (toolbar) {
                if (!!$scope.toolbarConfig["show" + toolbar]) {
                    $scope.toolbarConfig["show" + toolbar] = false;
                } else {
                    $timeout(function () {
                        $scope.toolbarConfig["show" + toolbar] = true;
                    });
                }
            };

            $scope.switchDatePicker = function (index) {
                $scope.datePickerFlag = [false, false, false, false];
                if (angular.isDefined(index)) {
                    $scope.datePickerFlag[index] = true;
                }
            };

            $scope.checkDate = function (obj, startFiled, endFiled) {
                var timeFormatObj = ybWidget.CheckDate(obj[startFiled], obj[endFiled]);
                if (!!timeFormatObj.tStart) {
                    obj[startFiled] = timeFormatObj.tStart;
                }
                if (!!timeFormatObj.tEnd) {
                    obj[endFiled] = timeFormatObj.tEnd;
                }
            };

            $scope.search = function (curpage) {
                getDataList(curpage);
            };

            $scope.reset = function () {
                $scope.condition = {
                    isService :$scope.isTJ? $scope.curUser.isService:undefined
                };

                if ($scope.isJCHK) {
                    $scope.condition.countryVOS = $scope.curUser.associateCountryVOS;
                }
            };

            function getBillIds() {
                $scope.exportParam.sectionParam.ids = [];
                angular.forEach($scope.dataList, function (item) {
                    if (!!item.isChecked) {
                        $scope.exportParam.sectionParam.ids.push(item.id);
                    }
                });
            }

            $scope.selectSingle = function (item, list, type) {
                if (!item.isChecked) {
                    $scope.markInfo["allChecked" + type] = false;
                } else {
                    if (!checkAll(list)) {
                        $scope.markInfo["allChecked" + type] = false;
                    } else {
                        $scope.markInfo["allChecked" + type] = true;
                    }
                }

                if (type == 'Bill') {
                    getBillIds();
                }
                if (type == 'Monitoring') {
                    getMonitoringIds();
                }
            };

            function checkAll(list) {
                var selectAll = false;
                for (var i = 0, len = list.length; i < len; i++) {
                    if (!list[i].isChecked) {
                        selectAll = false;
                        break;
                    }
                    selectAll = true;
                }
                return selectAll;
            }

            $scope.selectAll = function (list, type) {
                angular.forEach(list, function (item) {
                    item.isChecked = $scope.markInfo["allChecked" + type];
                });

                if (type == 'Bill') {
                    getBillIds();
                }
                if (type == 'Monitoring') {
                    getMonitoringIds();
                }
            };

            function getPurchaseBill(curPage) {
                var service = "device";
                var reqUrl = "/purchaseRequest/list";
                var param = {};
                param.pageSize = $scope.pageInfoPurchase.pageSize;
                if (!!curPage) {
                    $scope.pageInfoPurchase.curPage = curPage;
                }
                param.pageNum = $scope.pageInfoPurchase.curPage;
                param.filters = angular.copy($scope.billCondition);
                param.filters.billStatus = "2";
                param.filters.seller = true;
                param.filters.isSale = 0;
                param.filters.notDirect = 1;
                param.filters.purchaseToSaleFlag = $scope.isJCHK ? 1 : null; // "自动制定销售意向"时采购转销售的标记

                if ($scope.isJCH) {
                    param.filters.contractFilter = 1;
                }

                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    angular.forEach(resp.value.list, function (item) {
                        item.isChecked = false;
                        item.createDateShow = $filter("YbDate")(item.createDate);
                        item.deliveryDateShow = $filter("YbDate")(item.deliveryDate);
                        item.purchaseLevel = item.purchaseTypeChildId ? item.typeDesc + "-" + item.purchaseTypeChildName : item.typeDesc;
                        item.sendType = item.sendTypeChildId ? item.shippingMethod + "-" + item.sendTypeChildName : item.shippingMethod;
                    });
                    $scope.pageInfoPurchase.totalRows = resp.value.total;
                    $scope.pageInfoPurchase.totalPages = resp.value.pages;

                    $scope.purchaseList = resp.value.list;
                });
            }

            $scope.getPurchaseBill = function () {
                getPurchaseBill(1);
                $scope.changeTab(2);
            };

            $scope.searchPurchaseBill = function (curPage) {
                getPurchaseBill(curPage);
            };

            $scope.resetPurchaseCondition = function () {
                $scope.billCondition = {};
            };
            $scope.clearAddress = function () {
                $scope.orderObj.headerInfo.receiverName = '';
                $scope.orderObj.headerInfo.receiverPhone ='';
                $scope.orderObj.headerInfo.receiveAddress = '';
                $scope.orderObj.headerInfo.addressCode = '';
            };
            $scope.searchAddress = function (receiverName, purchaseOrgId) {
                if (!purchaseOrgId) {
                    ybWidget.ShowToaster('warning', '请先选择客户');
                    return;
                }
                ybWidget.SelectDeliveryAddress({
                    deliveryName: receiverName,
                    clientOrgId: purchaseOrgId,
                    clientReceiveInfo: $scope.isZHJCH,
                    supplierOrgId: $scope.curOrgId
                }).then(function (data) {
                    $scope.orderObj.headerInfo.receiverName = data.receiverName;
                    $scope.orderObj.headerInfo.receiverPhone = data.receiverTel;
                    $scope.orderObj.headerInfo.receiveAddress = data.receiverAddress;
                    $scope.orderObj.headerInfo.addressCode = data.addressCode;
                });
            };

            $scope.dealerOrgIdCus = '';

            $scope.selectDealer = function () {
                $scope.jckFlag = false;
                var param = {
                    name: "客户",
                    type: "dealer"
                };
                ybWidget.SingleSelector(param).then(function (data) {
                    if (!!$scope.orderObj.headerInfo.purchaseOrgId && (data.dealerOrgId !== $scope.orderObj.headerInfo.purchaseOrgId)) {
                        clearMateriel();
                        $scope.clearAddress();
                        $scope.orderObj.headerInfo.totalSettlementPrice = null;
                        $scope.orderObj.headerInfo.totalDiscountPrice = null;

                    }
                    $scope.orderObj.headerInfo.purchaseOrgName = data.companyName;
                    if(window.JCHK_ORG_IDs.includes(data.platOrgId)){
                        $scope.jckClientId = data.platOrgId;
                    }else{
                        $scope.jckClientId = "";
                    }
                    $scope.orderObj.headerInfo.purchaseOrgId = data.dealerOrgId;
                    if(window.JCHK_ORG_IDs.includes(data.platOrgId)) {
                        $scope.jckFlag = true;
                    }
                    $scope.dealerOrgIdCus = $scope.isJCHK ? $scope.curOrgId : data.dealerOrgId;
                })


            };


            function clearMateriel(onlyClear) {
                $scope.orderObj.materialList = [];
                $scope.markInfo.allCheckedMaterial = false;
                $timeout(function () {
                    if (onlyClear) {
                        EventBus.Publish("clearMaterial");
                    } else {
                        EventBus.Publish("getMaterial");
                    }
                });
            }

            function getPurchaseDetail(billId) {
                var service = "device";
                var reqUrl = "/purchaseRequest/item";
                var param = {
                    billId: billId,
                    isSale: $scope.isJCHK ? 1 : null // "自动制定销售意向"时 根据机型排序的标记
                };
                $scope.jckFlag = false;
                ybHttp.Get(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    $scope.orderObj.headerInfo.createDate = new Date();
                    $scope.orderObj.headerInfo.deliveryDate = resp.value.deliveryDate;
                    $scope.orderObj.headerInfo.purchaseNo = resp.value.billNo;
                    $scope.orderObj.headerInfo.purchaseContractNo = resp.value.purchaseContractNo;
                    $scope.orderObj.headerInfo.purchaseOrgId = resp.value.purchaseOrgId;
                    $scope.orderObj.headerInfo.purchaseOrgName = resp.value.purchaseOrgName;
                    $scope.orderObj.headerInfo.supplierOrgId = resp.value.supplierOrgId;
                    $scope.orderObj.headerInfo.supplierOrgName = resp.value.supplierOrgName;
                    $scope.orderObj.headerInfo.purchaseLevelId = resp.value.purchaseType;
                    $scope.orderObj.headerInfo.purchaseLevelNameShow = resp.value.purchaseTypeChildId ? resp.value.typeDesc + "-" + resp.value.purchaseTypeChildName : resp.value.typeDesc;
                    $scope.orderObj.headerInfo.purchaseLevelName = resp.value.typeDesc;
                    $scope.orderObj.headerInfo.purchaseTypeChildId = resp.value.purchaseTypeChildId;
                    $scope.orderObj.headerInfo.purchaseTypeChildName = resp.value.purchaseTypeChildName;
                    $scope.orderObj.headerInfo.deliverTypeName = resp.value.shippingMethod;
                    $scope.orderObj.headerInfo.receiverName = resp.value.receiverName;
                    $scope.orderObj.headerInfo.receiverFax = resp.value.receiverFax;
                    $scope.orderObj.headerInfo.receiverPhone = resp.value.receiverTel;
                    $scope.orderObj.headerInfo.receiveAddress = resp.value.receiverAddress;
                    $scope.orderObj.headerInfo.addressCode = resp.value.addressCode;
                    $scope.orderObj.headerInfo.totalSettlementPrice = resp.value.totalValue;
                    $scope.orderObj.headerInfo.country = resp.value.country;
                    $scope.orderObj.headerInfo.remark = resp.value.remark;
                    $scope.orderObj.headerInfo.isImprove = resp.value.isImprove;
                    $scope.orderObj.headerInfo.isUrgentPrice = resp.value.isUrgentPrice;
                    $scope.orderObj.headerInfo.region = resp.value.region;
                    $scope.orderObj.headerInfo.contract = resp.value.contract;
                    $scope.orderObj.headerInfo.model = resp.value.model;
                    $scope.orderObj.headerInfo.sendTypeChildId = resp.value.sendTypeChildId;
                    $scope.orderObj.headerInfo.sendTypeChildName = resp.value.sendTypeChildName;
                    $scope.orderObj.headerInfo.deliverTypeId = resp.value.shippingMethodId;
                    $scope.orderObj.headerInfo.deliverTypeName = resp.value.shippingMethod;
                    $scope.orderObj.headerInfo.forward =resp.value.forward;
                    $scope.orderObj.headerInfo.isGift = 0;
                    $scope.orderObj.headerInfo.crmServiceNo = resp.value.crmServiceNo;
                    $scope.orderObj.headerInfo.currency = resp.value.currency;
                    $scope.orderObj.headerInfo.bxFlag = resp.value.bxFlag;
                    $scope.orderObj.headerInfo.billTypeMode = resp.value.billTypeMode;
                    console.log(resp.value.model)
                    // 塔机的为下拉框字典需要映射
                    if ($scope.isTJ) {
                        $scope.orderObj.headerInfo.modelName = $scope.TJJXList.find(c => c.code == $scope.orderObj.headerInfo.model)?.name
                        $scope.orderObj.headerInfo.model =  $scope.TJJXList.find(c => c.code == $scope.orderObj.headerInfo.model)
                        console.log($scope.orderObj.headerInfo.model)
                    }
                    if(window.JCHK_ORG_IDs.includes(resp.value.purchasePlatOrgId)){
                        $scope.jckFlag = true;
                    }
                    $scope.showTransferFlag = !!resp.value.showTransferFlag;
                    if($scope.showTransferFlag) {
                        ybWidget.GetTableCol($scope.editTbConf.tableCol, 'transferFlag').hidden = false;
                        ybWidget.GetTableCol($scope.autoEditTbConf.tableCol, 'transferFlag').hidden = false;
                    }

                    $scope.orderObj.headerInfo.targetOrgId = '';
                    $scope.orderObj.headerInfo.targetOrgName = '';

                   handleMaterial4AddAuto(resp.value.materialsList, true);
                });
            }
            // 进出口的零件的标准价最为调整后价格
            function JCKPirceAdjust (value = angular.copy($scope.materialListAutoOri)){
                // 如果为非机构的供货商需将 进出口的零件的标准价最为调整后价格
                console.log("初始",value)
                let arr = value.filter(item => item.standardPrice == 0 || !!!item.standardPrice)
                if (!arr || arr.length < 1) {
                   return
                }
                console.log("校验通过",arr)
                let materialsNoArr = []
                arr.forEach(item => {
                    materialsNoArr.push(item.materialsNo)
                });
                var service = "device";
                var reqUrl = "/materials/purchaseMaterialsList";
                var param = {
                    filters: {
                        materialsNos: materialsNoArr.join(','),
                        orgId: $scope.curOrgId,
                    },
                    pageNum: 1,
                    pageSize: arr.length
                };
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    arr.forEach(i => {
                        let arrList = resp.value.list.filter(item => item.materialsNo == i.materialsNo)
                        i.unitPriceAfterAdjust = arrList[0]?.standardPrice
                        // 获取到调整后单价后 调整后总价也要重新计算
                        i.totalPriceAfterAdjust = $filter("decimalCover")(ybWidget.Times(i.amountAfterAdjust, i.unitPriceAfterAdjust), 2);

                    });
                    $scope.orderObj.materialList = value
                })
            }
            function handleMaterial4AddAuto(data, isFirstHandle) {
                angular.forEach(data, function (item) {
                    item.materialsDes = item.materialsDes || item.materialsDesc;

                    item.estimatedShippingDateShow = $filter("YbDate")(item.estimatedShippingDate, 'yyyy-MM-dd HH:mm:ss');

                    item.isNeedRaise = isNeedRaise($scope.orderObj.headerInfo, item);
                    // 17398需求：
                    // lastNum 是该需求所需，只有进出口 采购申请多次转销售订单时，调整后数量 取 未创建的数量lastNum。
                    // 非进出口 调整后数量 取 申请数量qty
                    item.amountAfterAdjust = item.lastNum || item.qty;

                    if ($scope.isDL || $scope.isZHL) {
                        // 道路筑路：零件的交货日期 取 采购申请 明细行的 交货日期
                        isFirstHandle && (item.requestDeliveryDate = new Date(item.deliveryDate));
                    } else {
                        item.requestDeliveryDate = new Date();
                    }

                    item.transferFlag = 1;
                    if ($scope.isJCHK && $scope.isOutSupplier) {
                        // 18860需求：(进出口定制)
                        // 如果供货商是非平台企业，调整后价格取进出口的标准价
                        item.unitPriceAfterAdjust = item.standardPrice || 0;
                    } else {
                        item.unitPriceAfterAdjust = item.settlementPrice;
                    }

                    item.totalPriceAfterAdjust = ((item.settlementPrice||0) * item.amountAfterAdjust).toFixed(2);

                    if (item.isRaise) {
                        item.isChecked = true;
                        // 需求要求：注释掉前端 加价*1.05的逻辑(挖机紧急采购方式)
                        // item.unitPriceAfterAdjust = $filter("decimalCover")(raisePrice(item.unitPriceAfterAdjust), 2);
                        item.unitPriceAfterAdjust = $filter("decimalCover")(item.unitPriceAfterAdjust, 2);
                        item.totalPriceAfterAdjust = $filter("decimalCover")(ybWidget.Times(item.unitPriceAfterAdjust, item.amountAfterAdjust), 2);
                    }
                    if($scope.isNY){
                        //折扣比例（调整后单价/单价）
                        if(!item.price){
                            item.discountRate=0;
                        }else{
                            item.discountRate= $filter("decimalCover")(ybWidget.Divide(item.unitPriceAfterAdjust ,item.price), 2);
                        }
                    }
                    pickingBillMaterialChange(item)
                });
                $scope.orderObj.materialList = data;
                setTotalPriceAdjust();

                if (isFirstHandle) {
                    $scope.materialListAutoOri = angular.copy(data); // 自动制定销售意向时，保存原始的零件信息
                }
            }

            $scope.checkItem = function (item, dataField) {
                var tempPrice = "";
                item.addRateType = (!!item.addRateType?item.addRateType:(!!$scope.addRateType?$scope.addRateType:1));
                if (item['isChecked'] === false) {
                    tempPrice = ybWidget.Divide(item.unitPriceAfterAdjust, (1+0.05*item.addRateType));
                } else {
                    tempPrice = ybWidget.Times(item.unitPriceAfterAdjust, (1+0.05*item.addRateType));
                }
                item.unitPriceAfterAdjust = $filter("decimalCover")(tempPrice, 2);
                item.totalPriceAfterAdjust = ybWidget.Times(item.unitPriceAfterAdjust, item.amountAfterAdjust);

                switch (dataField) {
                    case 'isNeedRaise':
                        item.isRaise = Number(item.isNeedRaise);
                        setTotalPriceAdjust();
                        break;
                    default:
                        break;
                }
                item.isChecked ? item.isRaise = 1 : item.isRaise = 0;

            };

            function isNeedRaise(headerInfo, material) {
                if (headerInfo.isUrgentPrice && headerInfo.purchaseLevelId === '1' && !headerInfo.isImprove) {
                    ybWidget.GetTableCol($scope.editTbConf.tableCol, 'isNeedRaise').hidden = false;
                    $scope.editTbConf.scrollWidth = 1990;

                    ybWidget.GetTableCol($scope.autoEditTbConf.tableCol, 'isNeedRaise').hidden = false;
                    $scope.autoEditTbConf.scrollWidth = 1990;
                }
                return !!material.isRaise;
            }

            function raisePrice(price, addRateType) {
                return ybWidget.Times(price, (1+0.05*(!!addRateType?addRateType:1)));
            }

            function getPurchaseLevel() {
                var service = "device";
                var reqUrl = "/dataDictionary/searchList";
                var param = {
                    parentCode: "CGJB"
                };
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    $scope.purchaseLevelList = resp.value;
                })
            }

            $scope.makeIntention = function (type, { billId, country, id }, needCheckCountry) {
                $scope.actionType = type;
                $scope.orderObj.headerInfo.createType = type;
                $scope.tabFlag.type = 0;

                ybWidget.GetTableCol($scope.editTbConf.tableCol, 'estimatedShippingDateShow').hidden = true;
                ybWidget.GetTableCol($scope.editTbConf.tableCol, 'standDeliveryTime').hidden = true;
                ybWidget.GetTableCol($scope.autoEditTbConf.tableCol, 'estimatedShippingDateShow').hidden = true;
                ybWidget.GetTableCol($scope.autoEditTbConf.tableCol, 'standDeliveryTime').hidden = true;

                if (type === 1) { // 1 手动创建
                    $scope.orderObj.headerInfo.createDate = +new Date();
                    $scope.orderObj.headerInfo.isGift = 0;

                    if ($scope.isSCH) {
                        $scope.orderObj.headerInfo.purchaseLevelId = '1';
                        $scope.orderObj.headerInfo.purchaseLevelName = '紧急';
                        $scope.orderObj.headerInfo.settleTypeName = '到付';
                        if (ybConfig.isEnvProd()) {
                            $scope.orderObj.headerInfo.deliverTypeId = '01';
                            $scope.orderObj.headerInfo.deliverTypeName = '物流';
                        } else {
                            $scope.orderObj.headerInfo.deliverTypeId = '001';
                            $scope.orderObj.headerInfo.deliverTypeName = '随物流';
                        }
                    }

                    $scope.giftFlag = false;
                    $scope.changeTab(1);
                    $scope.tabFlag.name = tabFlag[0];
                } else { 
                    if ($scope.isJCHK && needCheckCountry && !!country && !$scope.countries.find(o => o.name == country)) {
                        ybWidget.ShowMessage('没有国家和地区权限!', MESG_TYPE.Error)
                        return
                    }

                    if (type === 0) { // 0 采购申请创建
                        getPurchaseDetail(billId);
                        $scope.changeTab(3);
                        $scope.tabFlag.name = tabFlag[2];
                    } else if (type === 3) { // 3 按合同创建
                        getContracDetail(id);
                        $scope.changeTab(9);
                        $scope.tabFlag.name = tabFlag[5];
                    }

                    ybWidget.GetTableCol($scope.editTbConf.tableCol, 'qty').input = false;
                    ybWidget.GetTableCol($scope.editTbConf.tableCol, 'qty').inputType = "";
                    ybWidget.GetTableCol($scope.editTbConf.tableCol, 'amountAfterAdjust').input = true;
                    ybWidget.GetTableCol($scope.editTbConf.tableCol, 'amountAfterAdjust').inputType = "numAdjust";

                    ybWidget.GetTableCol($scope.autoEditTbConf.tableCol, 'qty').input = false;
                    ybWidget.GetTableCol($scope.autoEditTbConf.tableCol, 'qty').inputType = "";
                    ybWidget.GetTableCol($scope.autoEditTbConf.tableCol, 'amountAfterAdjust').input = true;
                    ybWidget.GetTableCol($scope.autoEditTbConf.tableCol, 'amountAfterAdjust').inputType = "numAdjust";
                }

                if ($scope.isWJ) {
                    $scope.orderObj.headerInfo.settleTypeName = "到付";
                }
            };
            $scope.selectBuyerName = function () {
                var param = {
                    name: "采购员",
                    type: "businessStaff"
                };
                ybWidget.SingleSelector(param).then(function (data) {
                    $scope.orderObj.headerInfo.buyerName = data.name;
                    $scope.orderObj.headerInfo.buyerId = data.userId;
                });
            };

            $scope.selMateriel = function (e) {
                if (!$scope.orderObj.headerInfo.purchaseOrgName) {
                    ybWidget.ShowToaster('error', '请选择客户');
                    return;
                }
                if ($scope.isJCHK && !$scope.supplyOrgId) {
                    // 进出口专用(手动制定、编辑、调整页面)
                    ybWidget.ShowToaster('error', '请选择供货商');
                    return;
                }

                if (!!$scope.toolbarConfig.showMateriel) {
                    e.stopPropagation();
                } else {
                    $timeout(function () {
                        $scope.toolbarConfig.showMateriel = true;
                        EventBus.Publish("getMaterial");
                    });
                }
            };

            $scope.importMateriel = function () {
                if (!$scope.orderObj.headerInfo.purchaseOrgId) {
                    ybWidget.ShowToaster('error', '请选择客户');
                    return;
                }

                if ($scope.isJCHK && !$scope.supplyOrgId) {
                    // 进出口专用(手动制定、编辑、调整页面)
                    ybWidget.ShowToaster('error', '请选择供货商');
                    return;
                }

                var param = {
                    name: "零件",
                    templateReqService: "device",
                    templateReqUrl: "/saleIntention/download",
                    importReqService: "device",
                    importReqUrl: "/saleIntention/import",
                    importErrorUrl: "",
                    dealerOrgId: $scope.orderObj.headerInfo.purchaseOrgId,
                    targetOrgId: $scope.supplyOrgId
                };
                ybWidget.ImportFile(param).then(function (data) {
                    angular.forEach(data, function (item) {
                        item.isChecked = false;
                        item.totalPriceAfterAdjust = $filter("decimalCover")(ybWidget.Times(item.amountAfterAdjust, item.unitPriceAfterAdjust), 2);
                        pickingBillMaterialChange(item)
                        if($scope.isNY){
                            //折扣比例（调整后单价/单价）
                            if(!item.price){
                                item.discountRate=0;
                            }else{
                                item.discountRate= $filter("decimalCover")(ybWidget.Divide(item.unitPriceAfterAdjust
                                    ,item.price), 2);
                            }
                        }
                    });
                    $scope.orderObj.materialList = angular.copy(data);
                    setTotal();
                });
            };

            $scope.importWaixiaoPrice = function () {
                var param = {
                    name: "外销单价",
                    templateReqService: "device",
                    templateReqUrl: "/downloadFile/excelTemplate",
                    templateCondition: {
                        excelFileName: "SaleIntenImportExportPrice.xls"
                    },
                    importReqService: "device",
                    importReqUrl: "/saleIntention/importMaterialExportPrice",
                    importErrorUrl: "",
                    otherParams: {
                        billNo:  $scope.orderObj.headerInfo.saleNo || $scope.orderObj.headerInfo.purchaseNo
                    }
                };
                ybWidget.ImportFile(param).then(function (data) {
                    let needUpdateTotalExportPrice = false
                    $scope.orderObj.materialList.forEach(om => {
                        const mTmp = data.find(d => d.materialsNo == om.materialsNo)
                        if (mTmp) {
                            needUpdateTotalExportPrice = true
                            om.exportPrice = mTmp.exportPrice
                            om.totalExportPrice = $filter("decimalCover")(ybWidget.Times(om.amountAfterAdjust||0, om.exportPrice||0), 2);
                        }
                    });
                    needUpdateTotalExportPrice && setTotalExportPrice();
                });
            };

            $scope.adjustDelMateriel = function (index, e) {
                ybWidget.ShowMessage("确定要删除该记录吗？", MESG_TYPE.Ask).then(function () {
                    $scope.orderObj.materialList.splice(index, 1);
                    e.stopPropagation();
                    setTotal()

                    reSetDeliveryDateByMaterialsMax();
                });
            };

            $scope.frozenMateriel = function (index, e) {
                ybWidget.ShowMessage("确定要冻结该零件发货吗？", MESG_TYPE.Ask).then(function () {
                     $scope.orderObj.materialList[index].isFrozen = 1;
                     var service = "device";
                     var reqUrl = "/saleIntention/frozen";
                     var param = [];
                     param.push($scope.orderObj.materialList[index])
                     frozenData(service, reqUrl, param)

                    e.stopPropagation();

                });
            };


            $scope.unFrozenMateriel = function (index, e) {
                ybWidget.ShowMessage("确定要解冻该零件发货吗？", MESG_TYPE.Ask).then(function () {
                     $scope.orderObj.materialList[index].isFrozen = 0;
                     var service = "device";
                     var reqUrl = "/saleIntention/frozen";
                     var param = [];
                     param.push($scope.orderObj.materialList[index])
                     frozenData(service, reqUrl, param)
                    e.stopPropagation();
                });
            };

            $scope.frozenAllData = function (isFrozen) {
                var service = "device";
                var reqUrl = "/saleIntention/frozen";
                // if ($scope.orderObj.headerInfo.status === '1' && $scope.orderObj.materialList.length === 0) {
                //     ybWidget.ShowToaster('error', '零件不可为空');
                //     return;
                // }
                var msg = "确定要冻结所有零件的发货吗？";
                if (isFrozen !==1)
                {
                    msg = "确定要解冻所有零件的发货吗？";
                }
                var param = angular.copy($scope.orderObj.materialList);

                ybWidget.ShowMessage(msg, MESG_TYPE.Ask).then(function () {
                    angular.forEach(param, function (item) {
                        item.isFrozen = isFrozen;
                     });
                     frozenData(service, reqUrl, param);
                     $scope.changeTab(0);
               });


            };

            function frozenData(service, reqUrl, param,isFrozen) {
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }

                    ybWidget.ShowToaster('success', '操作成功');

                });
            }

            $scope.delMateriel = function (item, index, e) {
                ybWidget.ShowMessage("确定要删除该记录吗？", MESG_TYPE.Ask).then(function () {
                    $scope.orderObj.materialList.splice(index, 1);
                    EventBus.Publish("setMaterial", item.materialsNo);
                    e.stopPropagation();
                    setTotal()

                    reSetDeliveryDateByMaterialsMax();
                });
            };

            $scope.batchDelMateriel = function () {
                var selectedCount = 0;
                for (var i = 0, len = $scope.orderObj.materialList.length; i < len; i++) {
                    if (!!$scope.orderObj.materialList[i].isChecked) {
                        selectedCount++;
                    }
                }
                if (!selectedCount) {
                    ybWidget.ShowMessage('请选择需要删除的行');
                    return;
                }
                ybWidget.ShowMessage("确定要删除选中的记录吗？", MESG_TYPE.Ask).then(function () {
                    for (var i = $scope.orderObj.materialList.length - 1; i >= 0; i--) {
                        if (!!$scope.orderObj.materialList[i].isChecked) {
                            $scope.orderObj.materialList.splice(i, 1);
                        }
                    }
                    if ($scope.orderObj.materialList.length === 0) {
                        $scope.markInfo.allCheckedMaterial = false;
                    }
                    EventBus.Publish("setMaterial");
                    setTotal()

                    reSetDeliveryDateByMaterialsMax();
                });
            };

            function setPrice(item, colItem) {
                item.qtyErr = false;
                if (!item[colItem] || parseFloat(item[colItem]) <= 0) {
                    item.qtyErr = true;
                    return;
                }
                if (item.qty > 99999999.99) {
                    item.qty = 99999999.99;
                }
                item.amountAfterAdjust = item.qty;
                if (angular.isUndefined(item[colItem]) || item[colItem] === "") {
                    item.applyTotalPrice = "";
                } else {
                    item.applyTotalPrice = $filter("decimalCover")(ybWidget.Times(item.qty, item.price), 2);
                }
                if (!!item.unitPriceAfterAdjust) {
                    item.totalPriceAfterAdjust = $filter("decimalCover")(ybWidget.Times(item.amountAfterAdjust||0, item.unitPriceAfterAdjust), 2);
                    setTotalPriceAdjust();
                }
            }

            function checkUnitPriceAfterAdjust(item, isByPriceSchme, type) {
                item.priceAdjustShowErr = false;
                item.priceAdjustErr = false;
                item.priceAdjustLowerErr = false;

                if ((!item.unitPriceAfterAdjust || parseFloat(item.unitPriceAfterAdjust) <= 0) && type !== "noPrice") {
                    item.priceAdjustErr = true;
                    item.priceAdjustShowErr = true;
                } else {
                    if (($scope.isJCH || $scope.isNJ)&& !isByPriceSchme) {
                        // 判断"调整后单价"是否修改
                        if (item.unitPriceAfterAdjust != item.unitPriceAfterAdjustOrig) {
                            item.modifyPriceFlag = 1
                            if (item.unitPriceAfterAdjust < item.unitPriceAfterAdjustOrig && !$scope.btnPermission.sellIntentionPriceCanLower) {
                                item.priceAdjustLowerErr = true;
                                item.priceAdjustShowErr = true;
                            }
                        } else {
                            item.modifyPriceFlag = 0
                        }
                    }
                }

                return item.priceAdjustShowErr;
            }

            function setAdjustPrice(item, colItem, isByPriceSchme) {
                item.qtyAdjustErr = false;
                if (!item.amountAfterAdjust || parseFloat(item.amountAfterAdjust) <= 0) {
                    item.qtyAdjustErr = true;
                    return;
                }

                // 校验调整后单价
                checkUnitPriceAfterAdjust(item, isByPriceSchme);

                if (item.amountAfterAdjust > 99999999.99) {
                    item.amountAfterAdjust = 99999999.99;
                }
                if (angular.isUndefined(item[colItem]) || item[colItem] === "") {
                    item.totalPriceAfterAdjust = ""
                } else {
                    item.totalPriceAfterAdjust = $filter("decimalCover")(ybWidget.Times(item.amountAfterAdjust, item.unitPriceAfterAdjust), 2);
                }
                setTotalPriceAdjust();
                if($scope.isNY){
                    //折扣比例（调整后单价/单价）
                    if(!item.price){
                        item.discountRate=0;
                    }else{
                        item.discountRate= $filter("decimalCover")(ybWidget.Divide(item.unitPriceAfterAdjust
                            ,item.price), 2);
                    }

                }
            }

            function setTotalPriceAdjust() {
                var totalPriceAdjustTmp = 0;
                angular.forEach($scope.orderObj.materialList, function (item) {
                    totalPriceAdjustTmp = ybWidget.Plus(totalPriceAdjustTmp, parseFloat(item.totalPriceAfterAdjust||0));
                });
                $scope.orderObj.headerInfo.totalDiscountPrice = $filter("decimalCover")(totalPriceAdjustTmp, 2);
            }

            function setExportPrice(item) {
                // 校验外销单价
                checkExportPrice(item);

                item.totalExportPrice = $filter("decimalCover")(ybWidget.Times(item.amountAfterAdjust||0, item.exportPrice||0), 2);
                setTotalExportPrice();
            }

            function setTotalExportPrice() {
                var totalExportPriceTmp = 0;
                $scope.orderObj.materialList.forEach(item => {
                    totalExportPriceTmp = ybWidget.Plus(totalExportPriceTmp, parseFloat(item.totalExportPrice||0));
                });
                $scope.orderObj.headerInfo.totalExportPrice = $filter("decimalCover")(totalExportPriceTmp, 2);
            };

            $scope.showErrTip = function (item, type) {
                if (!!item[type+"Err"]||!!item[type+"ExceedErr"]) {
                    item[type+"ShowErr"] = true
                }
            };

            $scope.hideErrTip = function (item, type) {
                item[type+"ShowErr"] = false
            };

            $scope.setPrice = function (item, colItem) {
                if (colItem === "qty") {
                    // 申请数量 发生改变
                    setPrice(item, colItem);
                }
                if (colItem === "amountAfterAdjust") {
                    // 调整后数量 发生变化
                    setAdjustPrice(item, colItem);
                }
                // 申请数量变了，调整后数量同步变；或者调整后数量直接变， 均会 导致外销金额，和外销总价也跟着变。
                setExportPrice(item)
            };

            $scope.setAdjustPrice = function (item, colItem) {
                // 调整后单价 发生变化
                setAdjustPrice(item, colItem)
            };

            $scope.setWaixiaoPrice = function (item) {
                // 外销单价 发生变化
                setExportPrice(item);
            };

            $scope.switchListDatePicker = function (item) {
                angular.forEach($scope.orderObj.materialList, function (item) {
                    item.showDatePicker = false;
                });
                item.showDatePicker = true;
            };

            EventBus.Subscribe("onMaterialChange", handleMaterialChange);

            function handleMaterialChange() {
                var totalPriceTmp = 0;
                var totalPriceAdjustTmp = 0;
                angular.forEach($scope.orderObj.materialList, function (item) {
                    totalPriceTmp = ybWidget.Plus(totalPriceTmp, parseFloat(item.applyTotalPrice||0));
                    totalPriceAdjustTmp = ybWidget.Plus(totalPriceAdjustTmp, parseFloat(item.totalPriceAfterAdjust||0));
                    if($scope.isNY){
                        //折扣比例（调整后单价/单价）
                        if(!item.price){
                            item.discountRate=0;
                        }else{
                            item.discountRate= $filter("decimalCover")(ybWidget.Divide(item.unitPriceAfterAdjust
                                ,item.price), 2);
                        }
                    }
                });
                $scope.orderObj.headerInfo.totalSettlementPrice = $filter("decimalCover")(totalPriceTmp, 2);
                $scope.orderObj.headerInfo.totalDiscountPrice = $filter("decimalCover")(totalPriceAdjustTmp, 2);
            }

            function setTotal() {
                var totalPriceTmp = 0;
                var totalPriceAdjustTmp = 0;
                var totalExportPriceTmp = 0;
                angular.forEach($scope.orderObj.materialList, function (item) {
                    totalPriceTmp = ybWidget.Plus(totalPriceTmp, parseFloat(item.applyTotalPrice||0));
                    totalPriceAdjustTmp = ybWidget.Plus(totalPriceAdjustTmp, parseFloat(item.totalPriceAfterAdjust||0));
                    totalExportPriceTmp = ybWidget.Plus(totalExportPriceTmp, parseFloat(item.totalExportPrice||0));
                });
                $scope.orderObj.headerInfo.totalSettlementPrice = $filter("decimalCover")(totalPriceTmp, 2);
                $scope.orderObj.headerInfo.totalDiscountPrice = $filter("decimalCover")(totalPriceAdjustTmp, 2);
                $scope.orderObj.headerInfo.totalExportPrice = $filter("decimalCover")(totalExportPriceTmp, 2);
            }

            $scope.$on("$destroy", function () {
                EventBus.Unsubscribe("onMaterialChange", handleMaterialChange);
            });

            function setPriceScheme(item, index, priceScheme) {
                var unitPriceAfterAdjust;
                if (angular.isUndefined(item.amountAfterAdjust) || item.amountAfterAdjust === "") {
                    item.amountAfterAdjust = item.qty;
                }
                item.priceSchemeId = priceScheme.activityId;
                item.priceSchemeName = priceScheme.name;

                if (item.isRaise && ($scope.tabFlag.index === 3 || $scope.tabFlag.index === 5)) {
                    unitPriceAfterAdjust = $filter("decimalCover")(raisePrice(priceScheme.discountPrice, item.addRateType), 2);
                } else {
                    unitPriceAfterAdjust = $filter("decimalCover")(priceScheme.discountPrice, 2);
                }

                if ($scope.isNY) {
                    // 徐工能源，调整后单价 向上取整。
                    unitPriceAfterAdjust = String(Math.ceil(unitPriceAfterAdjust||0));
                    //折扣比例（调整后单价/单价）
                    if(!item.price){
                        item.discountRate=0;
                    }else{
                        item.discountRate= $filter("decimalCover")(ybWidget.Divide(unitPriceAfterAdjust
                            ,item.price), 2);
                    }
                }

                $scope.orderObj.materialList[index].unitPriceAfterAdjust = unitPriceAfterAdjust;
                if (item.amountAfterAdjust !== "") {
                    // 调整后单价发生变化
                    setAdjustPrice(item, "amountAfterAdjust", true);
                }
            }
            function setPriceSchemeWX(item, index, priceScheme) {
                //外销单价 exportPrice
                var exportPrice;
                // 调整后数量 amountAfterAdjust
                if (angular.isUndefined(item.amountAfterAdjust) || item.amountAfterAdjust === "") {
                    item.amountAfterAdjust = item.qty;
                }
                item.exportPriceSchemeId = priceScheme.activityId;
                item.exportPriceSchemeName = priceScheme.name;
                // isRaose 是否加价
                if (item.isRaise && ($scope.tabFlag.index === 3 || $scope.tabFlag.index === 5)) {
                    exportPrice = $filter("decimalCover")(raisePrice(priceScheme.discountPrice, item.addRateType), 2);
                } else {
                    exportPrice = $filter("decimalCover")(priceScheme.discountPrice, 2);
                }


                $scope.orderObj.materialList[index].exportPrice = exportPrice;
                if (item.exportPrice !== "") {
                    // 调整后单价发生变化
                    $scope.setWaixiaoPrice(item,"exportPrice")
                }
            }
            let countryPre = ''
            $scope.onCountryChange = function() {
                if (countryPre !== $scope.orderObj.headerInfo.country) {
                    // 国家改变，接收单位是挖机时，清除价格方案
                    if ($scope.supplyOrgId && window.WJ_ORG_IDs.includes($scope.supplyOrgId) && $scope.orderObj.materialList.length > 0) {
                        angular.forEach($scope.orderObj.materialList, function (item, index) {
                            $scope.clearPriceScheme(item, index);
                        })
                    }
                }
                countryPre = $scope.orderObj.headerInfo.country;
            }

            //选择价格方案后回调
            $scope.chosePriceScheme = function (item, index) {
                var clientId = $scope.orderObj.headerInfo.purchaseOrgId;
                if (!clientId) {
                    ybWidget.ShowToaster('error', '请选择客户');
                    return;
                }

                if ($scope.isJCHK && !$scope.supplyOrgId) {
                    // 进出口专用(手动制定、编辑、调整页面 + 自动制定、编辑)
                    ybWidget.ShowToaster('error', '请选择供货商');
                    return;
                }

                const jckPriceFlag = $scope.isJCHK && $scope.supplyOrgId != $scope.curOrgId;

                let schemeTypeVal = 0
                let apiParam = {}
                if (jckPriceFlag) {
                    schemeTypeVal = 1
                    apiParam = {
                        materialsNo: item.materialsNo,
                        supplierOrgId: $scope.supplyOrgId,
                        country: window.WJ_ORG_IDs.includes($scope.supplyOrgId) ? $scope.orderObj.headerInfo.country : undefined
                    }
                } else {
                    apiParam = {
                        materialsNo: item.materialsNo,
                        dealerOrgId: clientId
                    }
                }
                var param = {
                    schemeType: schemeTypeVal,
                    apiObj: {
                        param: apiParam
                    }
                };
                ybWidget.PriceSchemeSelector(param).then(function (data) {

                    setPriceScheme(item, index, data);
                })
            };


            

            //选择外销价格方案后回调  进出口专用
            $scope.chosePriceSchemeWX = function (item, index) {
                var clientId = $scope.orderObj.headerInfo.purchaseOrgId;
                if (!clientId) {
                    ybWidget.ShowToaster('error', '请选择客户');
                    return;
                }

                if ($scope.isJCHK && !$scope.supplyOrgId) {
                    // 进出口专用(手动制定、编辑、调整页面 + 自动制定、编辑)
                    ybWidget.ShowToaster('error', '请选择供货商');
                    return;
                }

                let schemeTypeVal = 0
                let apiParam = {}
                apiParam = {
                        materialsNo: item.materialsNo,
                        dealerOrgId: clientId
                }
                var param = {
                    schemeType: schemeTypeVal,
                    apiObj: {
                        param: apiParam
                    }
                };
                ybWidget.PriceSchemeSelector(param).then(function (data) {
                    setPriceSchemeWX(item, index, data);
                })
            };            

            function batchSetTransferFlag(transferFlag) {
                angular.forEach($scope.orderObj.materialList, function (item) {
                    item.transferFlag = transferFlag;
                });
            }

            /**
             * 批量设置价格方案
             * @param priceSchemeId 价格方案标志
             */
            function batchSetPriceScheme(priceSchemeId) {

                for (var i = 0; i < $scope.orderObj.materialList.length; i++) {
                    var materialItem = $scope.orderObj.materialList[i];
                    var priceSchemeList = materialItem.marketingActivityPriceVOList || [];
                    var priceScheme = getPriceScheme(priceSchemeId, priceSchemeList);
                    console.log(priceSchemeList)

                    if (priceScheme != null) {
                        setPriceScheme(materialItem, i, priceScheme);
                    }
                }
                
                function getPriceScheme(id, list) {
                    for (var j = 0; j < list.length; j++) {
                        if (id == list[j].activityId) {
                            return list[j];
                        }
                    }
                    return null;
                }
            }
            /**
             * 批量设置外销价格方案
             * @param priceSchemeId 价格方案标志
             */
            function batchSetPriceSchemeWX(priceSchemeId) {

                for (var i = 0; i < $scope.orderObj.materialList.length; i++) {
                    var materialItem = $scope.orderObj.materialList[i];
                    var priceSchemeList = materialItem.dealerMarketingActivityList || [];
                    var priceScheme = getPriceScheme(priceSchemeId, priceSchemeList);
                    console.log(priceSchemeId)
                    console.log(priceSchemeList)
                    if (priceScheme != null) {
                        setPriceSchemeWX(materialItem, i, priceScheme);
                    }
                }

                function getPriceScheme(id, list) {
                    for (var j = 0; j < list.length; j++) {
                        if (id == list[j].activityId) {
                            return list[j];
                        }
                    }
                    return null;
                }
            }
            /**
             * 批量选择价格方案
             * 自动制定销售意向（新增、编辑）
             */
            $scope.batchChosePriceScheme = function () {
                var clientId = $scope.orderObj.headerInfo.purchaseOrgId;
                if (!clientId) {
                    ybWidget.ShowToaster('error', '请选择客户');
                    return;
                }

                if ($scope.isJCHK && !$scope.supplyOrgId) {
                    ybWidget.ShowToaster('error', '请选择供货商');
                    return;
                }

                let schemeTypeVal = 0
                let apiParam = {}
                if ($scope.isJCHK) {
                    schemeTypeVal = 1
                    apiParam = {
                        supplierOrgId: $scope.supplyOrgId,
                        country: window.WJ_ORG_IDs.includes($scope.supplyOrgId) ? $scope.orderObj.headerInfo.country : undefined
                    }
                } else {
                    apiParam = {
                        dealerOrgId: clientId
                    }
                }
                var param = {
                    isBatch: true,
                    schemeType: schemeTypeVal,
                    apiObj: {
                        param: apiParam
                    }
                };
                ybWidget.PriceSchemeSelector(param).then(function (data) {
                    batchSetPriceScheme(data.id);
                });
            };

            $scope.batchSetTransferFlag = function () {
                var param = {
                };
                ybWidget.TransferFlagSelector(param).then(function (data) {
                    batchSetTransferFlag(data);
                });
            };




            /**
             * 批量选择外销价格方案 进出口专用
             * 自动制定销售意向（新增、编辑）
             */
            $scope.batchChosePriceSchemeWX = function () {
                var clientId = $scope.orderObj.headerInfo.purchaseOrgId;
                if (!clientId) {
                    ybWidget.ShowToaster('error', '请选择客户');
                    return;
                }

                if ($scope.isJCHK && !$scope.supplyOrgId) {
                    ybWidget.ShowToaster('error', '请选择供货商');
                    return;
                }

                let schemeTypeVal = 0
                let apiParam = {}
                apiParam = {
                        dealerOrgId: clientId
                    }
                
                var param = {
                    isBatch: true,
                    schemeType: schemeTypeVal,
                    apiObj: {
                        param: apiParam
                    }
                };
                ybWidget.PriceSchemeSelector(param).then(function (data) {
                    batchSetPriceSchemeWX(data.id);
                });
            };

            $scope.batchSetTransferFlag = function () {
                var param = {
                };
                ybWidget.TransferFlagSelector(param).then(function (data) {
                    batchSetTransferFlag(data);
                });
            };

            /**
             * 批量选择价格方案
             * 手动制定销售意向（新增、编辑）
             */
            $scope.batchChosePriceSchemeForManual = function () {
                if (!$scope.isJCHK || $scope.isOutSupplier) {
                    // 非进出口 手动 和 自动 一样的逻辑
                    $scope.batchChosePriceScheme();
                    return;
                }

                // 进出口账号登录
                var param = {
                    isBatch: true,
                    schemeType: 1,
                    apiObj: {
                        param: {
                            supplierOrgId: $scope.supplyOrgId,
                            country: window.WJ_ORG_IDs.includes($scope.supplyOrgId) ? $scope.orderObj.headerInfo.country : undefined
                        }
                    }
                };
                ybWidget.PriceSchemeSelector(param).then(function (data) {
                    batchSetPriceScheme(data.id);
                });
            };

            //清除价格方案
            $scope.clearPriceScheme = function (item,index) {
                item.isRaise = 0;
                item.isChecked = false;
                item.priceSchemeId = "";
                item.priceSchemeName = "";
                if (item.isRaise && $scope.tabFlag.index === 3) {
                    item.unitPriceAfterAdjust = $filter("decimalCover")(raisePrice(item.price, item.addRateType), 2);
                } else {
                    item.unitPriceAfterAdjust = item.price;
                }
                item.totalPriceAfterAdjust = $filter("decimalCover")(ybWidget.Times(item.unitPriceAfterAdjust, item.amountAfterAdjust), 2);
                if($scope.isNY){
                    //折扣比例（调整后单价/单价）
                    if(!item.price){
                        item.discountRate=0;
                    }else{
                        item.discountRate= $filter("decimalCover")(ybWidget.Divide(item.unitPriceAfterAdjust
                            ,item.price), 2);
                    }
                }
                // 当接收单位为挖机时候，删除价格方案时候价格则为0
                if (window.WJ_ORG_IDs.includes($scope.orderObj.headerInfo.targetOrgId) && $scope.isJCHK) {
                    item.unitPriceAfterAdjust = 0
                }
                if (parseFloat(item.unitPriceAfterAdjust) > 0) {
                    item.priceAdjustErr = false;
                    return;
                }
                setTotalPriceAdjust();
            };
            //清除价格方案
            $scope.clearPriceSchemeWX = function (item,index) {
                item.exportPrice = 0;
                item.exportPriceSchemeId = '';
                item.exportPriceSchemeName = '';
                $scope.setWaixiaoPrice(item,"exportPrice")
                
            };
            function getDetail(saleIntentionId) {
                var service = "device";
                var reqUrl = "/saleIntention/item";
                var param = {};
                param.id = saleIntentionId;
                return ybHttp.Get(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp.value, MESG_TYPE.Error);
                        return false;
                    }
                    resp.value.headerInfo.distributionTypeShow = $filter("ProgressStatus")(resp.value.headerInfo.distributionType, "distributionType");
                    angular.forEach(resp.value.materialList, function (item) {
                        item.requestDeliveryDate = new Date(item.requestDeliveryDate);
                        item.unitPriceAfterAdjustOrig = item.unitPriceAfterAdjust;
                        item.modifyPriceTimeShow = $filter("YbDate")(item.modifyPriceTime, 'yyyy-MM-dd HH:mm:ss');
                        item.isFrozenShow = $filter("TrueOrFalse")(item.isFrozen);
                    });
                     // 塔机的为下拉框字典需要映射
                     if ($scope.isTJ) {
                        resp.value.headerInfo.modelName = $scope.TJJXList.find(c => c.code ==  resp.value.headerInfo.model)?.name
                        resp.value.headerInfo.model =  $scope.TJJXList.find(c => c.code ==  resp.value.headerInfo.model)
                        $scope.detailMap[22].field = 'modelName'
                        $scope.viewTbConf.tableCol[7].dataField = 'machineModelName'
                        resp.value.materialList.forEach(item => {
                            item.machineModelName = item.machineModel ?  $scope.TJJXList.find(c => c.code == item.machineModel)?.name : ''
                            item.machineModel = item.machineModel ?  $scope.TJJXList.find(c => c.code == item.machineModel) : ''
                        })
                    }
                    return resp.value;
                });
            }

            $scope.editData = function (item) {
                getDetail(item.id).then(function (data) {
                    if (!data) {
                        return;
                    }
                    $scope.jckClientId = data.headerInfo.purchasePlatOrgId;

                    //进出口时，判断是否平台企业
                    if($scope.isJCHK && !data.headerInfo.isPlatCompany){
                        $scope.supplyOrgId = $scope.curOrgId;
                        $scope.isOutSupplier = true;//外采
                    }else{
                        $scope.supplyOrgId = data.headerInfo.targetOrgId;
                        $scope.isOutSupplier = false;
                    }

                    $scope.showTransferFlag = !!(data.headerInfo.showTransferFlag);
                    if($scope.showTransferFlag) {
                        ybWidget.GetTableCol($scope.editTbConf.tableCol, 'transferFlag').hidden = false;
                        ybWidget.GetTableCol($scope.autoEditTbConf.tableCol, 'transferFlag').hidden = false;
                    }

                    $scope.dealerOrgIdCus = $scope.isJCHK && data.headerInfo.isPlatCompany ? $scope.curOrgId : data.headerInfo.purchaseOrgId;

                    data.headerInfo.deliveryDate = $filter("YbDate")(data.headerInfo.deliveryDate);
                    data.headerInfo.purchaseLevelNameShow = data.headerInfo.purchaseTypeChildId ? data.headerInfo.purchaseLevelName + "-" + data.headerInfo.purchaseTypeChildName : data.headerInfo.purchaseLevelName;
                    $scope.tabFlag.type = 1;
                    if (data.headerInfo.status === '1') {
                        $scope.editMaterialList = angular.copy(data.materialList);
                    }
                    if(window.JCHK_ORG_IDs.includes(data.headerInfo.purchasePlatOrgId)) {
                        $scope.jckFlag = true;
                        if(!!data.headerInfo.giftFlag) {
                            data.headerInfo.isGift = '1';
                        }else {
                            data.headerInfo.isGift = '0';
                        }
                    }else {
                        $scope.jckFlag = false;
                        data.headerInfo.isGift = '0';
                    }

                    if (item.createType === 0) { // 自动制定(采购申请)
                        $scope.changeTab(3);
                    } else if(item.createType === 3) { // 按合同创建
                        $scope.changeTab(9);
                    } else { // 手动制定、外部接口创建
                        $scope.changeTab(1);
                    }

                    angular.forEach(data.materialList, function (item) {
                        pickingBillMaterialChange(item)
                        item.estimatedShippingDateShow = $filter("YbDate")(item.estimatedShippingDate, 'yyyy-MM-dd HH:mm:ss');
                    });
                    $scope.actionType = 1;
                    $scope.orderObj = data;
                    $scope.tabFlag.name = tabFlag[1];

                    ybWidget.GetTableCol($scope.editTbConf.tableCol, 'qty').input = false;
                    ybWidget.GetTableCol($scope.editTbConf.tableCol, 'qty').inputType = "";
                    ybWidget.GetTableCol($scope.editTbConf.tableCol, 'amountAfterAdjust').input = true;
                    ybWidget.GetTableCol($scope.editTbConf.tableCol, 'amountAfterAdjust').inputType = "numAdjust";

                    ybWidget.GetTableCol($scope.autoEditTbConf.tableCol, 'qty').input = false;
                    ybWidget.GetTableCol($scope.autoEditTbConf.tableCol, 'qty').inputType = "";
                    ybWidget.GetTableCol($scope.autoEditTbConf.tableCol, 'amountAfterAdjust').input = true;
                    ybWidget.GetTableCol($scope.autoEditTbConf.tableCol, 'amountAfterAdjust').inputType = "numAdjust";

                    const cType = data.headerInfo.createType
                    if ((cType === 0 || cType === 3) && data.headerInfo.isUrgentPrice === 1) {
                        ybWidget.GetTableCol($scope.editTbConf.tableCol, 'isNeedRaise').hidden = false;

                        ybWidget.GetTableCol($scope.autoEditTbConf.tableCol, 'isNeedRaise').hidden = false;

                        angular.forEach($scope.orderObj.materialList, function (item) {
                            item.isRaise === 1 ? item.isChecked = true : item.isChecked = false;
                        });

                    } else {
                        ybWidget.GetTableCol($scope.editTbConf.tableCol, 'isNeedRaise').hidden = true;

                        ybWidget.GetTableCol($scope.autoEditTbConf.tableCol, 'isNeedRaise').hidden = true;
                    }
                });
            };

            $scope.adjustBill = function (item,type) {
                $scope.replaceMaterialFlag = false;
                getDetail(item.id).then(function (data) {
                    if (!data) {
                        return;
                    }

                    //进出口时，判断是否平台企业
                    if($scope.isJCHK && !data.headerInfo.isPlatCompany){
                        $scope.supplyOrgId = $scope.curOrgId;
                        $scope.isOutSupplier = true;//外采
                    }else{
                        $scope.supplyOrgId = data.headerInfo.targetOrgId;
                        $scope.isOutSupplier = false;
                    }

                    if (data.headerInfo.status === '1') {
                        $scope.editMaterialList = angular.copy(data.materialList);
                    }
                    $scope.forward = data.headerInfo.forward;
                    data.headerInfo.forward = $filter("TrueOrFalse")(data.headerInfo.forward);
                    data.headerInfo.deliverTypeNameShow = data.headerInfo.sendTypeChildId ? data.headerInfo.deliverTypeName + "-" + data.headerInfo.sendTypeChildName : data.headerInfo.deliverTypeName;
                    data.headerInfo.purchaseLevelNameShow = data.headerInfo.purchaseTypeChildId ? data.headerInfo.purchaseLevelName + "-" + data.headerInfo.purchaseTypeChildName : data.headerInfo.purchaseLevelName;
                    // 调整单价和调整去不同的页面
                    if (type == 'price') {
                        $scope.changeTab(10);
                    }else {
                        $scope.changeTab(5);
                    }
                    $scope.orderObj = data;
                    $scope.orderObj.headerInfo.giftFlagShow = '否';
                    $scope.detailMap.forEach((item) => {
                        if(item.field === 'giftFlagShow') {
                            if(window.JCHK_ORG_IDs.includes($scope.orderObj.headerInfo.purchasePlatOrgId)) {
                                item.isShow = true;
                                if(!!$scope.orderObj.headerInfo.giftFlag) {
                                    $scope.orderObj.headerInfo.giftFlagShow = '是';
                                }
                            }else {
                                item.isShow = false;
                            }
                        }
                        if(item.field === 'totalExportPrice') {
                            item.isShow = false;
                        }
                    });
                    $scope.addRateType = null;
                    $scope.orderObj.headerInfo.createDateShow = $filter("YbDate")($scope.orderObj.headerInfo.createDate);
                    $scope.orderObj.headerInfo.deliveryDateShow = $filter("YbDate")($scope.orderObj.headerInfo.deliveryDate);
                    angular.forEach($scope.orderObj.materialList, function (item) {
                        item.requestDeliveryDateShow = $filter("YbDate")(item.requestDeliveryDate);
                        item.checkDisable = item.informedAmount > 0;
                        $scope.addRateType = item.addRateType;
                        item.estimatedShippingDateShow = $filter("YbDate")(item.estimatedShippingDate, 'yyyy-MM-dd HH:mm:ss');
                    });
                    $scope.bakList = angular.copy($scope.orderObj.materialList);

                    const cType = data.headerInfo.createType
                    if ((cType === 0 || cType === 3) && data.headerInfo.isUrgentPrice === 1) {

                        ybWidget.GetTableCol($scope.adjustTbConf.tableCol, 'isNeedRaise').hidden = false;
                        angular.forEach($scope.orderObj.materialList, function (item) {
                            item.isRaise === 1 ? item.isChecked = true : item.isChecked = false;
                        });

                    } else {

                        ybWidget.GetTableCol($scope.adjustTbConf.tableCol, 'isNeedRaise').hidden = true;
                    }
                });
            };
            $scope.replaceMaterialFlag = false;
            $scope.importReplaceMateriel = function () {

                var param = {
                    name: "替换零件",
                    templateReqService: "device",
                    templateReqUrl: "/purchaseRequest/downloadReplaceMaterialTemp",
                    importReqService: "device",
                    importReqUrl: "/saleIntention/importReplaceMaterial",
                    importErrorUrl: "",
                    dealerOrgId: $scope.orderObj.headerInfo.purchaseOrgId,
                    saleId: $scope.orderObj.headerInfo.id,
                };
                ybWidget.ImportFile(param).then(function (data) {
                    angular.forEach(data, function (item) {
                        item.isChecked = false;
                    });
                    $scope.orderObj.materialList = [];
                    $scope.orderObj.materialList = angular.copy(data);
                    angular.forEach($scope.orderObj.materialsList, function (item) {
                        item.qtyFormatErr = false;
                        if (item.isMinimumBuy && ybWidget.Remainder(item.qty, item.minimumBuy) > 0) {
                            item.qtyFormatErr = true;
                        }
                        item.addRateType = $scope.addRateType;
                    });
                    $scope.editMaterialList = $scope.orderObj.materialList;
                    $scope.replaceMaterialFlag = true;
                });
            };
            $scope.adjustData = function (type,btntype) {
                var service = "device";
                var reqUrl = "/saleIntention/adjust";
                if (btntype == 'price') {
                    reqUrl = "/saleIntention/adjustPrice";
                }
                if ($scope.orderObj.headerInfo.status === '1' && $scope.orderObj.materialList.length === 0) {
                    ybWidget.ShowToaster('error', '零件不可为空');
                    return;
                }

                var listValid = checkListValid('noPrice', true); // 调整后单价和 noPrice 一样的逻辑，即不校验必填
                if (!listValid) {
                    return;
                }

                getAddList();
                $scope.orderObj.headerInfo.forward = $scope.forward
                var param = angular.copy($scope.orderObj);

                angular.forEach(param.materialList, function (item) {
                    if (item.isChecked === true) {
                        item.isRaise = 1;
                    }
                    if (item.isChecked === false) {
                        item.isRaise = 0;
                    }
                });
                if ($scope.orderObj.headerInfo.status === '1' && isDelMaterial() && !$scope.replaceMaterialFlag) {
                    ybWidget.ShowConfirm("确定要删除零件吗？", "删除原因").then(function (reason) {
                        param.deleteReason = reason;
                        adjustData(service, reqUrl, param);
                    });
                } else {
                    adjustData(service, reqUrl, param);
                }
            };

            function adjustData(service, reqUrl, param) {
                if ($scope.isTJ) {
                    const { code = '', name = '' } = $scope.orderObj.headerInfo.model || {}
                    param.headerInfo.model = code
                    param.materialList.forEach(item => {
                        item.machineModel = item.machineModel ? item.machineModel.code :''
                    })
                }
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    ybWidget.ShowToaster('success', '操作成功');
                    $scope.changeTab(0);
                });
                
                if($scope.isDL || $scope.isZHL){
                    getDataList();
                }  
            }

            function getAddList() {
                if (!$scope.bakList) {
                    return;
                }
                if($scope.replaceMaterialFlag){
                    return;
                }
                var addList = [];
                angular.forEach($scope.orderObj.materialList, function (item) {
                    var flag = true;
                    for (var i = 0; i < $scope.bakList.length; i++) {
                        if (item.materialsNo === $scope.bakList[i].materialsNo) {
                            flag = false;
                        }
                    }
                    if (flag) {
                        addList.push(item);
                    }
                });
                $scope.orderObj.bakMaterialsList = addList;
            }

            $scope.synPrice = function (id) {
                var service = "device";
                var reqUrl = "/saleIntention/synPrice";
                var param = {};
                param.id = id;
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    ybWidget.ShowToaster('success', '操作成功');
                    if ($scope.tabFlag.type === 0) {
                        getDataList(1);
                    } else {
                        getDataList();
                    }
                    $scope.changeTab(0);

                });
            };
            $scope.syncSaleIntention4NS  = function (id) {
                var service = "device";
                var reqUrl = "/saleIntention/syncSaleIntention4NS";
                var param = {};
                param.id = id;
                ybHttp.Get(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    ybWidget.ShowToaster('success', '操作成功');
                    if ($scope.tabFlag.type === 0) {
                        getDataList(1);
                    } else {
                        getDataList();
                    }
                    $scope.changeTab(0);

                });
            };

            $scope.bathSynPrice = function () {
                var synList = [];
                angular.forEach($scope.dataList, function (item) {
                    if (item.isChecked) {
                        synList.push(item.id);
                    }
                });
                if (synList.length === 0) {
                    ybWidget.ShowMessage('请选择可同步的数据', MESG_TYPE.Error);
                    return;
                }
                ybWidget.ShowMessage("确定要批量同步价格吗？", MESG_TYPE.Ask).then(function (data) {
                    var service = "device";
                    var reqUrl = "/saleIntention/bathSynPrice";
                    ybHttp.Post(service, reqUrl, synList).then(function (resp) {
                        if (resp.code !== 0) {
                            ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                            return;
                        }
                        ybWidget.ShowToaster('success', '操作成功');
                        if ($scope.tabFlag.type === 0) {
                            getDataList(1);
                        } else {
                            getDataList();
                        }
                    });
                })
            }

            function viewDetail(item, isCheckFlag) {
                $scope.isCheckFlag = isCheckFlag;
                $scope.tabFlag.name = isCheckFlag ? tabFlag[isCheckFlag] : tabFlag[3]
                getDetail(item.id).then(function (data) {
                    if (!data) {
                        return;
                    }
                    $scope.subTabFlag = [true, false];
                    $scope.changeTab(4);
                    data.headerInfo.deliverTypeNameShow = data.headerInfo.sendTypeChildId ? data.headerInfo.deliverTypeName + "-" + data.headerInfo.sendTypeChildName : data.headerInfo.deliverTypeName;
                    data.headerInfo.purchaseLevelNameShow = data.headerInfo.purchaseTypeChildId ? data.headerInfo.purchaseLevelName + "-" + data.headerInfo.purchaseTypeChildName : data.headerInfo.purchaseLevelName;
                    $scope.orderObj = data;
                    $scope.orderObj.headerInfo.giftFlagShow = '否';
                    $scope.detailMap.forEach((item) => {
                        if(item.field === 'giftFlagShow') {
                            if(window.JCHK_ORG_IDs.includes($scope.orderObj.headerInfo.purchasePlatOrgId)) {
                               item.isShow = true;
                               if(!!$scope.orderObj.headerInfo.giftFlag) {
                                   $scope.orderObj.headerInfo.giftFlagShow = '是';
                               }
                           }else {
                                item.isShow = false;
                            }
                        }
                        if(item.field === 'totalExportPrice') {
                            item.isShow = !!$scope.isJCHK; // 仅进出口显示
                        }
                    });
                    $scope.orderObj.headerInfo.createDateShow = $filter("YbDate")($scope.orderObj.headerInfo.createDate)
                    $scope.orderObj.headerInfo.deliveryDateShow = $filter("YbDate")($scope.orderObj.headerInfo.deliveryDate)
                    angular.forEach($scope.orderObj.materialList, function (item) {
                        item.estimatedShippingDateShow = $filter("YbDate")(item.estimatedShippingDate, 'yyyy-MM-dd HH:mm:ss');
                        item.requestDeliveryDateShow = $filter("YbDate")(item.requestDeliveryDate);
                        pickingBillMaterialChange(item)
                    });

                    if (window.WJ_ORG_IDs.includes($scope.orderObj.headerInfo.targetOrgId) && $scope.isJCHK ) {
                        ybWidget.GetTableCol($scope.viewTbConf.tableCol, 'price').hidden = true;
                        ybWidget.GetTableCol($scope.viewTbConf.tableCol, 'applyTotalPrice').hidden = true;
                      }else if(!window.WJ_ORG_IDs.includes($scope.orderObj.headerInfo.targetOrgId) && $scope.isJCHK ) {
                        ybWidget.GetTableCol($scope.viewTbConf.tableCol, 'price').hidden = false;
                        ybWidget.GetTableCol($scope.viewTbConf.tableCol, 'applyTotalPrice').hidden = false;
                      } 
                });
            }

            $scope.getDeliveryNotice = function () {
                var service = "device";
                var reqUrl = "/deliveryNote/list";
                var param = {};
                param.pageNum = 0;
                param.pageSize = 0;
                param.filters = {
                    saleNo: $scope.orderObj.headerInfo.saleNo
                };
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    angular.forEach(resp.value.list, function (item) {
                        item.isReverseShow = $filter("ProgressStatus")(item.isReverse, "reverse");
                        item.createDateShow = $filter("YbDate")(item.createDate);
                        item.deliveryDateShow = $filter("YbDate")(item.deliveryDate)
                    });
                    $scope.deliveryList = resp.value.list;
                });
            };

            function checkExportPrice(item,type) {
                item.priceWaixiaojiaShowErr = false;
                item.priceWaixiaojiaErr = false;
                if(!!type&&type!='save'){
                    if ((!item.exportPrice || parseFloat(item.exportPrice) <= 0)) {
                        item.priceWaixiaojiaErr = true;
                        item.priceWaixiaojiaShowErr = true;
                     }
                }
                return item.priceWaixiaojiaShowErr;
            }

            function checkListValid(type, fromAdjust) {
                var isValid = true;
                for (var i = 0, len = $scope.orderObj.materialList.length; i < len; i++) {
                    if (!fromAdjust) {
                        if (!$scope.orderObj.materialList[i].qty || parseFloat($scope.orderObj.materialList[i].qty) <= 0 ) {
                            $scope.orderObj.materialList[i].qtyErr = true;
                            isValid = false;
                            break;
                        }
                    }

                    if (!fromAdjust || fromAdjust && ($scope.isDL || $scope.isZHL)) {
                        // 非调整时，所有公司都校验 交货日期
                        // 调整时，只有道路筑路 校验 交货日期
                        if (!$scope.orderObj.materialList[i].requestDeliveryDate) {
                            $scope.orderObj.materialList[i].dateErr = true;
                            isValid = false;
                            break;
                        }
                    }

                    // 校验调整后单价
                    if (checkUnitPriceAfterAdjust($scope.orderObj.materialList[i], false, type)) {
                        isValid = false;
                        break;
                    }

                    // 校验外销单价
                    if ($scope.isJCHK && checkExportPrice($scope.orderObj.materialList[i],type)) {
                        isValid = false;
                        break;
                    }
                    
                    //进出口校验适用机型不能为空
                    if ($scope.isJCHK && !$scope.orderObj.materialList[i].machineModel) {
                        $scope.orderObj.materialList[i].modelErr = true;
                        isValid = false;
                        break;
                    }
                }
                return isValid;
            }

            $scope.go2checkData = function (item, auditType) {
                viewDetail(item, auditType)
            };

            $scope.checkData = function (id, checkFlag) {
                var service = "device";
                var reqUrl = "/saleIntention/audit4JC";
                var param = {
                    "id": id,
                    "checkFlag": checkFlag
                }
                ybHttp.Get(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    ybWidget.ShowToaster('success', '操作成功');
                    getDataList(1)
                    $scope.changeTab(0)
                })
            };

            $scope.degreeCheckData = function (id, auditFlag) {
                var service = "device";
                var reqUrl = "/saleIntention/auditDegree4JC";
                var param = {
                    "id": id,
                    "auditFlag": auditFlag
                }
                ybHttp.Get(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    ybWidget.ShowToaster('success', '操作成功');
                    getDataList(1)
                    $scope.changeTab(0)
                })
            };

            $scope.saveData = UserContextService.Debounce(function(isValid, type) {
                if (!isValid) {
                    ybWidget.ShowToaster('error', '验证不通过，请正确填写页面信息');
                    $scope.submitted = true;
                    return;
                }
                var listValid = checkListValid(type);
                if (!listValid) {
                    return;
                }
                var service = "device";
                var reqUrl = "/saleIntention/save";
                if (type === "submit" || type === "noPrice") {
                    reqUrl = "/saleIntention/submit";
                    if ($scope.orderObj.materialList.length === 0) {
                        ybWidget.ShowToaster('error', '零件不可为空');
                        return;
                    }
                } else if (type === "settlement") {
                    reqUrl = "/saleIntention/balance";
                    if ($scope.orderObj.materialList.length === 0) {
                        ybWidget.ShowToaster('error', '零件不可为空');
                        return;
                    }
                }

                angular.forEach($scope.orderObj.materialList, function (item) {
                    if (item.isChecked === true) {
                        item.isRaise = 1;
                    }
                    if (item.isChecked === false) {
                        item.isRaise = 0;
                    }
                });

                var param = angular.copy($scope.orderObj);
                if(!!param.headerInfo.isGift && '1'===param.headerInfo.isGift) {
                    param.headerInfo.giftFlag = 1;
                }else {
                    param.headerInfo.giftFlag = 0;
                }

                if ($scope.tabFlag.type === 1 && $scope.orderObj.headerInfo.status === '1' && (type === "submit" || type === "noPrice") && isDelMaterial()) {
                    ybWidget.ShowConfirm("确定要删除零件吗？", "删除原因").then(function (reason) {
                        param.deleteReason = reason;
                        saveDataFunc(service, reqUrl, param, type);
                    });
                } else {
                    saveDataFunc(service, reqUrl, param, type);
                }
            }, 500);


            function saveDataFunc(service, reqUrl, param, type) {
                // 塔机的为下拉框字典 需要映射
                if ($scope.isTJ) {
                    const { code = '', name = '' } = $scope.orderObj.headerInfo.model || {}
                    param.headerInfo.model = code
                    param.materialList.forEach(item => {
                        item.machineModel = item.machineModel ? item.machineModel.code :''
                    })
                }
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }

                    if (type === "submit" && !($scope.isJCHK && $scope.activeFlag[1])) { // 进出口手动制定时，不跳转

                        const { saleIntentionId, autoAddFlag } = resp.value || {};

                        !autoAddFlag && ybWidget.ShowMessage("下发成功，是否立即创建发货通知单？", MESG_TYPE.Ask).then(function () {
                            $state.go("app.sales.deliveryNotice", {
                                id: saleIntentionId
                            })
                        }, function () {

                        })
                    }

                    ybWidget.ShowToaster('success', '操作成功');

                    if ($scope.tabFlag.type === 0) {
                        getDataList(1);
                    } else {
                        getDataList();
                    }

                    if (type === "settlement") {
                        $scope.changeTab(6);
                        var totalAmountCollected = 0;
                        angular.forEach($scope.orderObj.materialList, function (item) {
                            totalAmountCollected += Number(item.totalPriceAfterAdjust);
                        });
                        $scope.orderObj.headerInfo.amountCollected = totalAmountCollected;
                        $scope.orderObj.headerInfo.totalPrice = totalAmountCollected;
                        getReceiptTableList(resp.value);
                    } else {
                        $scope.changeTab(0)
                    }

                });
            }

            function getReceiptTableList(value) {
                var service = "device",
                    reqUrl = "/arap/detailList",
                    param = {
                        filters: {
                            orgId: $scope.orderObj.headerInfo.purchaseOrgId,
                            type: 0,
                            isSettle: 0,
                            isAll: 1,
                            billNo: value
                        }
                    };

                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    var df = "yyyy-MM-dd HH:mm:ss";
                    angular.forEach(resp.value.list, function (item) {
                        item.billSingleF = $filter("orderType")(item.billSingle);
                        item.billDateF = $filter("YbDate")(item.billDate, df);
                        item.isChecked = false;
                        item.checkPrice = item.remainPrice;
                    });
                    $scope.receiptTableInfo.dataList = resp.value.list;
                });
            }

            $scope.selectOperator = function () {
                var param = {
                    name: "经办人",
                    type: "agent",
                    supplierOrgId: ""
                };
                param.supplierOrgId = $scope.curOrgId || undefined;
                ybWidget.SingleSelector(param).then(function (data) {
                    $scope.orderObj.headerInfo.operatorId = data.userId;
                    $scope.orderObj.headerInfo.operatorName = data.name;
                })
            };

            function isDelMaterial() {
                var isDelMaterial = false;
                for (var i = 0; i < $scope.editMaterialList.length; i++) {
                    var isMaterialExist = false,
                        editMaterial = $scope.editMaterialList[i];

                    for (var j = 0; j < $scope.orderObj.materialList.length; j++) {
                        if (editMaterial.materialsNo === $scope.orderObj.materialList[j].materialsNo) {
                            isMaterialExist = true;
                            break;
                        }
                    }

                    if (!isMaterialExist) {
                        isDelMaterial = true;
                        break;
                    }
                }
                return isDelMaterial;
            }

            $scope.cancel = function () {
                if ($scope.actionType === 1) {
                    $scope.changeTab(0);
                } else if ($scope.actionType === 0) {
                    $scope.changeTab(2);
                } else if ($scope.actionType === 3) {
                    $scope.changeTab(8);
                }
            };

            function getMaterielCount(id) {
                var service = "device";
                var reqUrl = "/saleIntention/getDetailQty";
                var param = {
                    saleIntentionId: id
                };
                return ybHttp.Get(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    return resp.value;
                })
            };

            $scope.delData = function (id) {
                var service = "device";
                var reqUrl = "/saleIntention/remove";
                getMaterielCount(id).then(function (data) {
                    return ybWidget.ShowConfirm("此记录包含" + data + "条零件信息,确定要删除吗？", "删除原因")
                }).then(function (reason) {
                    var param = {
                        id: id,
                        deleteReason: reason
                    };
                    ybHttp.Post(service, reqUrl, param).then(function (resp) {
                        if (resp.code !== 0) {
                            ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                            return;
                        }
                        ybWidget.ShowToaster('success', '操作成功');
                        getDataList();
                    })
                });
            };

            $scope.importAttach = function (item) {
                var param = {
                    name: "附件",
                    hideTemplate: true,
                    ignoreFormat: true,
                    importReqService: "device",
                    importReqUrl: "/saleIntention/importAttach",
                    importErrorUrl: "",
                    billId: item.id
                };
                ybWidget.ImportFile(param).then(function (data) {
                    getDataList(1);
                });
            };


            $scope.saveAddReceipt = function (isValid) {
                if (!isValid) {
                    $scope.submitted = true;
                    return;
                }

                var param = {};
                var service = "device";
                var reqUrl = "/check/add";
                param.headerInfo = angular.copy($scope.orderObj.headerInfo);
                param.headerInfo.discountPrice = param.headerInfo.discountPrice || 0;
                param.headerInfo.checkType = 0;
                param.headerInfo.supplierOrgId = $scope.curOrgId;
                param.headerInfo.supplierOrgName = $scope.curOrg.companyName;
                param.headerInfo.settleType = 0;
                param.headerInfo.isDealer = 1;
                param.detailList = [];
                angular.forEach($scope.receiptTableInfo.dataList, function (item) {
                    param.detailList.push({
                        arapDetailId: item.id,
                        billDate: item.billDate,
                        billNo: item.billNo,
                        billId: item.billId,
                        billSingle: item.billSingle,
                        checkPrice: item.checkPrice,
                        totalPrice: item.totalPrice,
                        receivePrice: item.remainPrice
                    });

                });

                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    ybWidget.ShowToaster('success', '操作成功');
                    $scope.changeTab(0);
                });
            };


            /**
             * ***************************************** 单据详情 开始 *****************************************
             */
            $scope.orderDetailObj = {};
            $scope.orderDetailTableInfo = {
                markInfo: {
                    curRow: -1
                },
                tableConfig: {
                    scrollWidth: 1270,
                    tableCol: [{
                            name: "零件编号",
                            dataField: "materialsNo",
                            width: 150,
                            isShow: true,
                            isFixed: false,
                            toSort: false
                        },
                        {
                            name: "零件中文名",
                            dataField: "materialsDes",
                            width: 150,
                            isShow: true,
                            isFixed: false,
                            toSort: false
                        },
                        {
                            name: "零件分类",
                            width: 100,
                            dataField: "sortName"
                        },
                        {
                            name: "单位",
                            dataField: "unit",
                            width: 80,
                            isShow: true,
                            isFixed: false,
                            toSort: false
                        },
                        {
                            name: "默认储位",
                            dataField: "stockLocation",
                            width: 150,
                            isShow: true,
                            isFixed: false,
                            toSort: false
                        },
                        {
                            name: "订单总数",
                            dataField: "amountAfterAdjust",
                            width: 80,
                            isShow: true,
                            isFixed: false,
                            toSort: false
                        },
                        {
                            name: "已发数量",
                            dataField: "sendQty",
                            width: 100,
                            isShow: true,
                            isFixed: false,
                            toSort: false
                        },
                        {
                            name: "本次发货",
                            dataField: "deliveryQty",
                            width: 100,
                            isShow: true,
                            isFixed: false,
                            toSort: false
                        },
                        {
                            name: "单价",
                            dataField: "unitPriceAfterAdjust",
                            width: 100,
                            isShow: true,
                            isFixed: false,
                            toSort: false
                        },
                        {
                            name: "已出库数",
                            dataField: "inventoryOutAmount",
                            width: 100,
                            isShow: true,
                            isFixed: false,
                            toSort: false
                        },
                        {
                            name: "实际库存",
                            dataField: "enableNum",
                            width: 100,
                            isShow: true,
                            isFixed: false,
                            toSort: false
                        },
                        {
                            name: "意向占用",
                            dataField: "intentionNum",
                            width: 100,
                            isShow: true,
                            isFixed: false,
                            toSort: false
                        },
                        {
                            name: "发货占用",
                            dataField: "deliveryNum",
                            width: 100,
                            isShow: true,
                            isFixed: false,
                            toSort: false
                        },
                        {
                            name: "安全库存",
                            dataField: "logState",
                            width: 100,
                            isShow: true,
                            isFixed: false,
                            toSort: false
                        },
                        {
                            name: "危险库存",
                            dataField: "logState",
                            width: 100,
                            isShow: true,
                            isFixed: false,
                            toSort: false
                        },
                        {
                          name: "标准交期",
                          width: 150,
                          dataField: "standDeliveryTime",
                        },
                        {
                            name: "预计发货日期",
                            dataField: "estimatedShippingDateShow",
                            width: 130,
                        },
                    ]
                },
                dataList: []
            };

            function viewOrderDetail(item) {
                switch (item.billSingle) {
                    case "XGFT":
                        $scope.orderDetailObj = {};
                        $scope.orderDetailTableInfo.dataList = [];
                        getXGFTOrderDetail(item.billId).then(function (data) {
                            if (!data) {
                                return;
                            }
                            $scope.orderDetailObj = data.headerInfo;
                            $scope.orderDetailTableInfo.dataList = data.materialList;
                            $scope.changeTab(7);
                        });
                        break;
                    default:
                        break;
                }

            }

            function getXGFTOrderDetail(billId) {
                var service = "device";
                var reqUrl = "/deliveryNote/item";
                var param = {};
                param.id = billId;
                return ybHttp.Get(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return false;
                    }
                    return resp.value;
                });
            }

            /**
             * ***************************************** 单据详情 结束 *****************************************
             */

            $scope.selectWarehouse = function () {
                ybWidget.WarehouseSelector().then(function (data) {
                    if (!!$scope.orderObj.headerInfo.outArea && (data.areaCode !== $scope.orderObj.headerInfo.outArea)) {
                        $scope.orderObj.headerInfo.outArea = "";
                        $scope.orderObj.headerInfo.sapOutArea = "";
                    }
                    $scope.orderObj.headerInfo.outLocation = data.warehouseCode;
                })
            };

            //新增收款单时选择库区
            $scope.selectArea = function () {
                if (!$scope.orderObj.headerInfo.outLocation) {
                    ybWidget.ShowToaster('error', '请选择发出仓库');
                    return;
                }
                var param = {};
                param.warehouseCode = $scope.orderObj.headerInfo.outLocation;
                ybWidget.DepotAreaSelector(param).then(function (data) {
                    $scope.orderObj.headerInfo.outArea = data.areaCode;
                    $scope.orderObj.headerInfo.sapOutArea = data.sapCode;
                })
            };

            //清空仓库
            $scope.clearWarehouse = function () {
                $scope.orderObj.headerInfo.outArea = "";
                $scope.orderObj.headerInfo.sapOutArea = "";
                $scope.orderObj.headerInfo.outLocation = "";
            };


            //清空库区
            $scope.clearArea = function () {
                $scope.orderObj.headerInfo.outArea = "";
                $scope.orderObj.headerInfo.sapOutArea = "";
            };

            //新增收款时修改优惠金额
            $scope.changePreferentialAmount = function () {
                $scope.orderObj.headerInfo.realPrice = $scope.orderObj.headerInfo.amountCollected - $scope.orderObj.headerInfo.discountPrice;
                $scope.orderObj.headerInfo.realPrice < 0 ? $scope.orderObj.headerInfo.realPrice = 0 : $scope.orderObj.headerInfo.realPrice = $scope.orderObj.headerInfo.realPrice
            };


            /**
             * ***************************************** 大厂库存  开始 *****************************************
             */


            $scope.sapStockMap = {}

            // 处理手动制定销售意向
            EventBus.Subscribe("onMaterialSelect", pickingBillMaterialChange);

            function pickingBillMaterialChange(item) {
                // 处理大厂库存逻辑
                // 仅限基础、能源
                if (!$scope.isJCH && !$scope.isNY && !$scope.isNJ) return
                var service = 'device';
                var reqUrl = '/materialsSchedule/sapStock';
                var param = {
                    materialsNo: item.materialsNo
                };
                ybHttp.Get(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    $scope.sapStockMap[item.materialsNo] = resp.value || {}
                });
            }

            function dachangStock(item) {
                var param = {
                    title: '大厂库存',
                    data: item.detailVOList || []
                };
                ybWidget.DatasShow(param);
            }


            /**
             * ***************************************** 大厂库存  结束 *****************************************
             */


            function selectSupplierFunc() {
                if (!$scope.orderObj.headerInfo.purchaseOrgId) {
                    ybWidget.ShowToaster('error', '请选择客户');
                    return;
                }

                var param = {
                    name: "供货商",
                    type: "supplier"
                };

                return ybWidget.SingleSelector(param);
            }


            $scope.selectSupplier = function () {
                selectSupplierFunc().then(function (data) {
                    // 如果值为空或者选择相同的接收单位直接返回不做后续处理
                    if (!data.supplierOrgId || data.supplierOrgId === $scope.orderObj.headerInfo.targetOrgId) {
                        return;
                    }

                    $scope.orderObj.headerInfo.targetOrgId = data.supplierOrgId;
                    $scope.orderObj.headerInfo.targetOrgName = data.companyName;

                    if (!data.isPlatCompany) {
                        // 若不是平台注册企业，则显示进出口零件。（取进出口orgId）
                        $scope.supplyOrgId = $scope.curOrgId; // 取进出口
                        $scope.isOutSupplier = true;
                        $scope.dealerOrgIdCus = $scope.orderObj.headerInfo.purchaseOrgId;
                    } else {
                        $scope.supplyOrgId = data.supplierOrgId;
                        $scope.isOutSupplier = false;
                    }

                    // 重新选择接收单位后 清除零件
                    clearMateriel(true);
                })
            };

            $scope.clearSupplier = function () {
                $scope.orderObj.headerInfo.targetOrgId = '';
                $scope.orderObj.headerInfo.targetOrgName = '';
                $scope.supplyOrgId = '';

                clearMateriel(true);
            };

            $scope.selectSupplier4AddAuto = function() {
                selectSupplierFunc().then(function (data) {
                    console.log(data)
                    // 如果值为空或者选择相同的接收单位直接返回不做后续处理
                    if (!data.supplierOrgId || data.supplierOrgId === $scope.orderObj.headerInfo.targetOrgId) {
                        return;
                    }

                    $scope.supplyOrgId = data.supplierOrgId;
                    $scope.orderObj.headerInfo.targetOrgId = data.supplierOrgId;
                    $scope.orderObj.headerInfo.targetOrgName = data.companyName;
                    if (data.isPlatCompany) {
                        $scope.isOutSupplier = false;
                        // 平台企业，判断该企业下是否有所选零件
                        const params = {
                            purchaseNo: $scope.orderObj.headerInfo.purchaseNo,
                            supplierOrgId: data.supplierOrgId,
                            dealerOrgId: $scope.isJCHK ? $scope.orderObj.headerInfo.purchaseOrgId : "" // 进出口专用参数用来处理批量外销价格方案的
                        };
                        ybHttp.Get('device', '/saleIntention/getJckExchangeSaleDetails', params).then(function(resp) {
                            handleMaterial4AddAuto(resp.value);
                        })
                    } else {
                        //非平台机构调整价格
                        JCKPirceAdjust()
                        $scope.isOutSupplier = true;//外采供货商
                    }
                })
            };

            $scope.clearSupplierAddAuto = function () {
                $scope.orderObj.headerInfo.targetOrgId = '';
                $scope.orderObj.headerInfo.targetOrgName = '';

                $scope.orderObj.materialList = angular.copy($scope.materialListAutoOri); // 删除供货商时恢复原来的零件信息
            };

            $scope.printBill = function ({ id, saleNo, isPrint }) {
                var param = {
                    billId: [id],
                    printType: "SellIntention",
                    recordPrint: {
                        billNo: saleNo
                    }
                };
                ybWidget.SetIsPrintOrPreview(param).then(function() {
                    if (!isPrint) {
                        getDataList();
                    }
                });
            };

            $scope.printBill4Details = function (item) {
                handlePrint4Details([item]);
            };

            $scope.batchPrint4Details = function () {
                const selectedDatas4Detail = $scope.orderObj.materialList.filter(d => d.isChecked);
                if (selectedDatas4Detail.length === 0) {
                    ybWidget.ShowMessage('请选择需要打印的行');
                    return;
                }

                handlePrint4Details(selectedDatas4Detail);
            };

            function handlePrint4Details(data) {
                const { headerInfo } = angular.copy($scope.orderObj);
                var param = {
                    printType: "SellIntention",
                    printDataInfo: { headerInfo, materialList: data }
                };
                ybWidget.SetIsPrintOrPreview(param);
            }

            $scope.applyDel = function(itemId) {
                ybWidget.ShowConfirm("确定要删除吗？", "删除原因").then(function (reason) {
                    var param = {
                        id: itemId,
                        deleteApplicationReason: reason
                    };
                    ybHttp.Post("device", "/saleIntention/deleteApplicationSubmit", param).then(function (resp) {
                        if (resp.code !== 0) {
                            ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                            return;
                        }
                        ybWidget.ShowToaster('success', '操作成功');
                        getDataList();
                    });
                });
            };

            $scope.checkApplyDel = function(itemId) {
                ybWidget.AuditMsg({
                    passCb: function(val) {
                        return handleAudit (1, itemId, val)
                    },
                    refuseCb: function(val) {
                        return handleAudit (2, itemId, val)
                    }
                })
            };

            function handleAudit(type, itemId, msg) {
                var service = "device";
                var reqUrl = "";
                var param = { id: itemId };

                if (type == 1) {
                    // 通过
                    reqUrl = "/saleIntention/deleteApplicationAuditPass"
                } else if (type == 2) {
                    // 拒绝
                    if (!msg) {
                        ybWidget.ShowMessage("请填写审核意见", MESG_TYPE.Error);
                        return
                    }
                    reqUrl = "/saleIntention/deleteApplicationAuditRefuse"
                }
                param.deleteAuditOpinion = msg;

                return ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    ybWidget.ShowToaster('success', '操作成功');
                    getDataList();
                });
            };





            $scope.contractTbConf = {
                fixedWidth: 120,
                scrollWidth: 1200,
                tableCol: [{
                        name: "合同号",
                        dataField: "billNo",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "接收单位",
                        dataField: "supplierOrgName",
                        width: 180,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "客户名称",
                        dataField: "purchareOrgName",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "调度员",
                        dataField: "dispatcherName",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "发运方式",
                        dataField: "sendType",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "付款方式",
                        dataField: "payType",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "申请人",
                        dataField: "createName",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "申请时间",
                        dataField: "createDateShow",
                        width: 140,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        type: "operate",
                        name: "操作",
                        dataField: "",
                        width: 120,
                        isShow: true,
                        isFixed: true,
                    }
                ]
            };
            $scope.contractList = [];
            $scope.pageInfoContract = {
                totalPages: 1,
                totalRows: 0,
                pageSize: 10,
                curPage: 1
            };
            $scope.contractCondition = {};

            $scope.resetContractCondition = function () {
                $scope.contractCondition = {};
            };

            function getContracDetail(billId) {
                var service = "device";
                var reqUrl = "/contract/item";
                var param = { id: billId };
                ybHttp.Get(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    $scope.orderObj.headerInfo.contractNo = resp.value.billNo;

                    $scope.orderObj.headerInfo.purchaseOrgId = resp.value.purchaseOrgId;
                    $scope.orderObj.headerInfo.purchaseOrgName = resp.value.purchareOrgName;

                    $scope.orderObj.headerInfo.sendTypeChildId = resp.value.sendTypeChildId;
                    $scope.orderObj.headerInfo.sendTypeChildName = resp.value.sendTypeChildName;
                    $scope.orderObj.headerInfo.deliverTypeId = resp.value.shippingMethodId;
                    $scope.orderObj.headerInfo.deliverTypeName = resp.value.shippingMethod;

                    $scope.orderObj.headerInfo.remark = resp.value.remark;

                    $scope.orderObj.headerInfo.billTypeMode = '合同';
                    $scope.orderObj.headerInfo.createDate = new Date();
                    $scope.orderObj.headerInfo.deliveryDate = new Date();

                    handleMaterial4AddAuto(resp.value.materialsList, true);
                });
            }

            function getContractBill(curPage) {
                var service = "device";
                var reqUrl = "/contract/list";
                if (!!curPage) {
                    $scope.pageInfoContract.curPage = curPage;
                }
                var param = {
                    pageSize: $scope.pageInfoContract.pageSize,
                    pageNum: $scope.pageInfoContract.curPage,
                    filters: angular.copy($scope.contractCondition)
                };
                param.filters.isSale = 0;

                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    angular.forEach(resp.value.list, function (item) {
                        item.isChecked = false;
                        item.createDateShow = $filter("YbDate")(item.createDate, 'yyyy-MM-dd HH:mm:ss');
                        item.sendType = item.sendTypeChildId ? item.shippingMethod + "-" + item.sendTypeChildName : item.shippingMethod;
                    });
                    $scope.pageInfoContract.totalRows = resp.value.total;
                    $scope.pageInfoContract.totalPages = resp.value.pages;

                    $scope.contractList = resp.value.list;
                });
            }
            function getTJJXType(){
                var service = "device";
                var reqUrl = "/serviceBasicDataAgent/searchList";
                var param = {pCode:"TJJX"};
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    $scope.TJJXList =resp.value;
                });
            }
            $scope.getContractBill = function () {
                getContractBill(1);
                $scope.changeTab(8);
                //初始化
                $scope.orderObj.headerInfo.billTypeMode="合同";
            };

            $scope.searchContractBill = function (curPage) {
                getContractBill(curPage);
            };



            

            // 订单监控功能相关---start
            $scope.monitoringTbConf = {
                fixedWidth: 40,
                scrollWidth: 1200,
                tableCol: [{
                        name: "意向单号",
                        dataField: "saleNo",
                        width: 200,
                        isShow: true,
                        isFixed: false,
                        sortType: "",
                        // clickFn: "viewDetail",
                        clickFn: "viewMonitoringDetail",
                    },
                    {
                        name: "客户名称",
                        dataField: "purchaseOrgName",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                    },
                    // {
                    //     name: "订单总价",
                    //     dataField: "totalSettlementPrice",
                    //     width: 100,
                    //     isShow: true,
                    //     isFixed: false,
                    //     sortType: ""
                    // },
                    {
                        name: "调整总价",
                        dataField: "totalDiscountPrice",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        sortType: ""
                    },
                    {
                        name: "未下发金额",
                        dataField: "undistributedAmount",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        sortType: ""
                    },
                    {
                        name: "未出库金额",
                        dataField: "unshippedAmount",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        sortType: ""
                    },
                    {
                        name: "待开票金额",
                        dataField: "pendingInvoiceAmount",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        sortType: ""
                    },
                    {
                        name: "无法过账金额",
                        dataField: "unablePostAmount",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        sortType: ""
                    },
                    {
                        name: "采购级别",
                        dataField: "purchaseLevelName",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "创建人",
                        dataField: "createName",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "生成发货通知单的总价汇总",
                        dataField: "createDeliveryNoteTotalPrice",
                        width: 220,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "生成发货单已出库的单据总价汇总",
                        dataField: "createDeliveryNoteOutPrice",
                        width: 220,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "生成发货单已过账的单据总价汇总",
                        dataField: "createDeliveryNotePostingPrice",
                        width: 220,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "生成发货单已开票的单据总价汇总",
                        dataField: "createDeliveryNoteTicketPrice",
                        width: 220,
                        isShow: true,
                        isFixed: false,
                    },
                ]
            };
            $scope.monitoringList = [];
            $scope.pageInfoMonitoring = {
                totalPages: 1,
                totalRows: 0,
                pageSize: 10,
                curPage: 1
            };
            $scope.monitoringCondition = {};

            $scope.monitoringExportParam = {
                sectionUrl: ybHttp.RequestUrl("device", "/saleIntention/exportUnCompleteListSelected"),
                sectionParam: {
                    ids: []
                },
                allUrl: ybHttp.RequestUrl("device", "/saleIntention/exportUnCompleteListAll")
            };

            function getMonitoringIds() {
                $scope.monitoringExportParam.sectionParam.ids = [];
                angular.forEach($scope.monitoringList, function (item) {
                    if (!!item.isChecked) {
                        $scope.monitoringExportParam.sectionParam.ids.push(item.id);
                    }
                });
            }

            $scope.resetMonitoringCondition = function () {
                $scope.monitoringCondition = {};
            };

            function getMonitoringBill(curPage) {
                var service = "device";
                var reqUrl = "/saleIntention/unCompleteList";
                if (!!curPage) {
                    $scope.pageInfoMonitoring.curPage = curPage;
                }
                var param = {
                    pageSize: $scope.pageInfoMonitoring.pageSize,
                    pageNum: $scope.pageInfoMonitoring.curPage,
                    filters: angular.copy($scope.monitoringCondition)
                };
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    angular.forEach(resp.value.list, function (item) {
                        item.isChecked = false;
                        item.createDateShow = $filter("YbDate")(item.createDate, 'yyyy-MM-dd HH:mm:ss');
                        item.sendType = item.sendTypeChildId ? item.shippingMethod + "-" + item.sendTypeChildName : item.shippingMethod;
                    });
                    $scope.pageInfoMonitoring.totalRows = resp.value.total;
                    $scope.pageInfoMonitoring.totalPages = resp.value.pages;

                    $scope.monitoringList = resp.value.list;
                    console.log("$scope.monitoringList", $scope.monitoringList);
                });
            }

            $scope.getMonitoringBill = function () {
                getMonitoringBill(1);
                   // 获取统计数据
                getTmonitoringTotalData()
                $scope.changeTab(11);
            };
            $scope.searchMonitoringBill = function (curPage) {
                getMonitoringBill(curPage);
                getTmonitoringTotalData()
            };
            // 订单监控功能相关---end

            $scope.fahuoDateChange = function(val) {
                angular.forEach($scope.orderObj.materialList, function(item) {
                    item.requestDeliveryDate = val;
                })

                $scope.orderObj.headerInfo.deliveryDate = val;
                $scope.orderObj.headerInfo.deliveryDateShow = $filter("YbDate")(val);
            };

            $scope.jiaohuoDateChange = function() {
                reSetDeliveryDateByMaterialsMax()
            };

            function reSetDeliveryDateByMaterialsMax() {
                if (!$scope.isDL && !$scope.isZHL) return;

                let deliveryDates = $scope.orderObj.materialList.map(item => item.requestDeliveryDate).filter(Boolean);
                deliveryDates = deliveryDates.sort(function(a, b) {
                    if (a > b) return -1
                    if (a == b) return 0
                    if (a < b) return 1
                })
                $scope.orderObj.headerInfo.deliveryDate = deliveryDates[0];
                $scope.orderObj.headerInfo.deliveryDateShow = $filter("YbDate")(deliveryDates[0]);
            }

            // 订单监控总计数据---start---
            function getTmonitoringTotalData  (){
                var service = "device";
                var reqUrl = "/saleIntention/unCompleteListStatisticalSummary";
                var param = {
                    pageSize: $scope.pageInfoMonitoring.pageSize,
                    pageNum: $scope.pageInfoMonitoring.curPage,
                    filters: angular.copy($scope.monitoringCondition)
                };
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    console.log("订单监控总计数据 resp:",resp);
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    $scope.tmonitoringTotalData =resp.value;
                });
            }
            // 订单监控总计数据---end---

            (function () {
                getTJJXType()
                if ($scope.isJCHK) {
                    $scope.condition.countryVOS = $scope.curUser.associateCountryVOS;
                }

                $scope.condition.createName = $scope.curUser.name;
                $scope.monitoringCondition.createName = $scope.curUser.name;

                console.log("$stateParams:",$stateParams);

                // 如果从首页代办事项销售订单预警按钮跳转过来就将高级搜索条件的销售订单预警选项设为是
                
                if ($stateParams.flag){
                    console.log("从首页代办事项的销售订单预警跳转过来的");
                    $scope.condition.notCompletedForOver7DaysCond = 1;
                    $scope.condition.createName = $scope.curUser.name;
                }else if ($stateParams.isOrderMonitoring){
                    console.log("从首页销售订单监控跳转过来的");
                    getMonitoringBill(1);
                    // 获取订单监控统计数据
                    getTmonitoringTotalData()
                    $scope.changeTab(11);
                }
                
                var orderNo = $stateParams.billNo;
                if (orderNo) {
                    $scope.condition.saleNo = orderNo;
                    getDataList();
                } else {
                    var sellIntentionBillNo = window.sessionStorage.getItem("sellIntentionBillNo");
                    window.sessionStorage.removeItem("sellIntentionBillNo");
                    if (!!sellIntentionBillNo) {
                        $scope.condition.saleNo = sellIntentionBillNo;
                        getDataList().then(function (data) {
                            viewDetail(data[0]);
                        })
                    } else {
                        var saleOrderCountWaitAudit = $stateParams.saleOrderCountWaitAudit;
                        if(!!saleOrderCountWaitAudit){
                            $scope.condition.checkFlag = '10';
                        }
                        getDataList();
                    }
                }

                //采购申请页面，审核通过后如果立即新增销售订单，则直接跳转过来
                if (!!$stateParams.billId) {
                    $scope.makeIntention(0, { billId: $stateParams.billId });
                }

                getPurchaseLevel();
                $scope.setFixedWidth();
                UserContextService.SetBtnPermission(setBtnPermission);

                if ($scope.isJCHK) {
                    const countriesTmp = $scope.curUser.associateCountryVOS || [];
                    $scope.countries = countriesTmp.map(ct => ({ name: ct.countryName, code: ct.countryCode }));
                }
            })();
        }]);
})(window, window.angular);
